Fix migration guide mappings for i2o/o2i_ECPublicKey
[openssl.git] / apps / speed.c
1 /*
2  * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10
11 #undef SECONDS
12 #define SECONDS          3
13 #define PKEY_SECONDS    10
14
15 #define RSA_SECONDS     PKEY_SECONDS
16 #define DSA_SECONDS     PKEY_SECONDS
17 #define ECDSA_SECONDS   PKEY_SECONDS
18 #define ECDH_SECONDS    PKEY_SECONDS
19 #define EdDSA_SECONDS   PKEY_SECONDS
20 #define SM2_SECONDS     PKEY_SECONDS
21 #define FFDH_SECONDS    PKEY_SECONDS
22
23 /* We need to use some deprecated APIs */
24 #define OPENSSL_SUPPRESS_DEPRECATED
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <math.h>
30 #include "apps.h"
31 #include "progs.h"
32 #include <openssl/crypto.h>
33 #include <openssl/rand.h>
34 #include <openssl/err.h>
35 #include <openssl/evp.h>
36 #include <openssl/objects.h>
37 #include <openssl/core_names.h>
38 #include <openssl/async.h>
39 #if !defined(OPENSSL_SYS_MSDOS)
40 # include <unistd.h>
41 #endif
42
43 #if defined(__TANDEM)
44 # if defined(OPENSSL_TANDEM_FLOSS)
45 #  include <floss.h(floss_fork)>
46 # endif
47 #endif
48
49 #if defined(_WIN32)
50 # include <windows.h>
51 #endif
52
53 #include <openssl/bn.h>
54 #include <openssl/rsa.h>
55 #include "./testrsa.h"
56 #ifndef OPENSSL_NO_DH
57 # include <openssl/dh.h>
58 #endif
59 #include <openssl/x509.h>
60 #include <openssl/dsa.h>
61 #include "./testdsa.h"
62 #include <openssl/modes.h>
63
64 #ifndef HAVE_FORK
65 # if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_VXWORKS)
66 #  define HAVE_FORK 0
67 # else
68 #  define HAVE_FORK 1
69 # endif
70 #endif
71
72 #if HAVE_FORK
73 # undef NO_FORK
74 #else
75 # define NO_FORK
76 #endif
77
78 #define MAX_MISALIGNMENT 63
79 #define MAX_ECDH_SIZE   256
80 #define MISALIGN        64
81 #define MAX_FFDH_SIZE 1024
82
83 #ifndef RSA_DEFAULT_PRIME_NUM
84 # define RSA_DEFAULT_PRIME_NUM 2
85 #endif
86
87 typedef struct openssl_speed_sec_st {
88     int sym;
89     int rsa;
90     int dsa;
91     int ecdsa;
92     int ecdh;
93     int eddsa;
94     int sm2;
95     int ffdh;
96 } openssl_speed_sec_t;
97
98 static volatile int run = 0;
99
100 static int mr = 0;  /* machine-readeable output format to merge fork results */
101 static int usertime = 1;
102
103 static double Time_F(int s);
104 static void print_message(const char *s, long num, int length, int tm);
105 static void pkey_print_message(const char *str, const char *str2,
106                                long num, unsigned int bits, int sec);
107 static void print_result(int alg, int run_no, int count, double time_used);
108 #ifndef NO_FORK
109 static int do_multi(int multi, int size_num);
110 #endif
111
112 static const int lengths_list[] = {
113     16, 64, 256, 1024, 8 * 1024, 16 * 1024
114 };
115 #define SIZE_NUM         OSSL_NELEM(lengths_list)
116 static const int *lengths = lengths_list;
117
118 static const int aead_lengths_list[] = {
119     2, 31, 136, 1024, 8 * 1024, 16 * 1024
120 };
121
122 #define START   0
123 #define STOP    1
124
125 #ifdef SIGALRM
126
127 static void alarmed(int sig)
128 {
129     signal(SIGALRM, alarmed);
130     run = 0;
131 }
132
133 static double Time_F(int s)
134 {
135     double ret = app_tminterval(s, usertime);
136     if (s == STOP)
137         alarm(0);
138     return ret;
139 }
140
141 #elif defined(_WIN32)
142
143 # define SIGALRM -1
144
145 static unsigned int lapse;
146 static volatile unsigned int schlock;
147 static void alarm_win32(unsigned int secs)
148 {
149     lapse = secs * 1000;
150 }
151
152 # define alarm alarm_win32
153
154 static DWORD WINAPI sleepy(VOID * arg)
155 {
156     schlock = 1;
157     Sleep(lapse);
158     run = 0;
159     return 0;
160 }
161
162 static double Time_F(int s)
163 {
164     double ret;
165     static HANDLE thr;
166
167     if (s == START) {
168         schlock = 0;
169         thr = CreateThread(NULL, 4096, sleepy, NULL, 0, NULL);
170         if (thr == NULL) {
171             DWORD err = GetLastError();
172             BIO_printf(bio_err, "unable to CreateThread (%lu)", err);
173             ExitProcess(err);
174         }
175         while (!schlock)
176             Sleep(0);           /* scheduler spinlock */
177         ret = app_tminterval(s, usertime);
178     } else {
179         ret = app_tminterval(s, usertime);
180         if (run)
181             TerminateThread(thr, 0);
182         CloseHandle(thr);
183     }
184
185     return ret;
186 }
187 #else
188 # error "SIGALRM not defined and the platform is not Windows"
189 #endif
190
191 static void multiblock_speed(const EVP_CIPHER *evp_cipher, int lengths_single,
192                              const openssl_speed_sec_t *seconds);
193
194 static int opt_found(const char *name, unsigned int *result,
195                      const OPT_PAIR pairs[], unsigned int nbelem)
196 {
197     unsigned int idx;
198
199     for (idx = 0; idx < nbelem; ++idx, pairs++)
200         if (strcmp(name, pairs->name) == 0) {
201             *result = pairs->retval;
202             return 1;
203         }
204     return 0;
205 }
206 #define opt_found(value, pairs, result)\
207     opt_found(value, result, pairs, OSSL_NELEM(pairs))
208
209 typedef enum OPTION_choice {
210     OPT_COMMON,
211     OPT_ELAPSED, OPT_EVP, OPT_HMAC, OPT_DECRYPT, OPT_ENGINE, OPT_MULTI,
212     OPT_MR, OPT_MB, OPT_MISALIGN, OPT_ASYNCJOBS, OPT_R_ENUM, OPT_PROV_ENUM,
213     OPT_PRIMES, OPT_SECONDS, OPT_BYTES, OPT_AEAD, OPT_CMAC
214 } OPTION_CHOICE;
215
216 const OPTIONS speed_options[] = {
217     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [algorithm...]\n"},
218
219     OPT_SECTION("General"),
220     {"help", OPT_HELP, '-', "Display this summary"},
221     {"mb", OPT_MB, '-',
222      "Enable (tls1>=1) multi-block mode on EVP-named cipher"},
223     {"mr", OPT_MR, '-', "Produce machine readable output"},
224 #ifndef NO_FORK
225     {"multi", OPT_MULTI, 'p', "Run benchmarks in parallel"},
226 #endif
227 #ifndef OPENSSL_NO_ASYNC
228     {"async_jobs", OPT_ASYNCJOBS, 'p',
229      "Enable async mode and start specified number of jobs"},
230 #endif
231 #ifndef OPENSSL_NO_ENGINE
232     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
233 #endif
234     {"primes", OPT_PRIMES, 'p', "Specify number of primes (for RSA only)"},
235
236     OPT_SECTION("Selection"),
237     {"evp", OPT_EVP, 's', "Use EVP-named cipher or digest"},
238     {"hmac", OPT_HMAC, 's', "HMAC using EVP-named digest"},
239     {"cmac", OPT_CMAC, 's', "CMAC using EVP-named cipher"},
240     {"decrypt", OPT_DECRYPT, '-',
241      "Time decryption instead of encryption (only EVP)"},
242     {"aead", OPT_AEAD, '-',
243      "Benchmark EVP-named AEAD cipher in TLS-like sequence"},
244
245     OPT_SECTION("Timing"),
246     {"elapsed", OPT_ELAPSED, '-',
247      "Use wall-clock time instead of CPU user time as divisor"},
248     {"seconds", OPT_SECONDS, 'p',
249      "Run benchmarks for specified amount of seconds"},
250     {"bytes", OPT_BYTES, 'p',
251      "Run [non-PKI] benchmarks on custom-sized buffer"},
252     {"misalign", OPT_MISALIGN, 'p',
253      "Use specified offset to mis-align buffers"},
254
255     OPT_R_OPTIONS,
256     OPT_PROV_OPTIONS,
257
258     OPT_PARAMETERS(),
259     {"algorithm", 0, 0, "Algorithm(s) to test (optional; otherwise tests all)"},
260     {NULL}
261 };
262
263 enum {
264     D_MD2, D_MDC2, D_MD4, D_MD5, D_SHA1, D_RMD160,
265     D_SHA256, D_SHA512, D_WHIRLPOOL, D_HMAC,
266     D_CBC_DES, D_EDE3_DES, D_RC4, D_CBC_IDEA, D_CBC_SEED,
267     D_CBC_RC2, D_CBC_RC5, D_CBC_BF, D_CBC_CAST,
268     D_CBC_128_AES, D_CBC_192_AES, D_CBC_256_AES,
269     D_CBC_128_CML, D_CBC_192_CML, D_CBC_256_CML,
270     D_EVP, D_GHASH, D_RAND, D_EVP_CMAC, ALGOR_NUM
271 };
272 /* name of algorithms to test. MUST BE KEEP IN SYNC with above enum ! */
273 static const char *names[ALGOR_NUM] = {
274     "md2", "mdc2", "md4", "md5", "sha1", "rmd160",
275     "sha256", "sha512", "whirlpool", "hmac(md5)",
276     "des-cbc", "des-ede3", "rc4", "idea-cbc", "seed-cbc",
277     "rc2-cbc", "rc5-cbc", "blowfish", "cast-cbc",
278     "aes-128-cbc", "aes-192-cbc", "aes-256-cbc",
279     "camellia-128-cbc", "camellia-192-cbc", "camellia-256-cbc",
280     "evp", "ghash", "rand", "cmac"
281 };
282
283 /* list of configured algorithm (remaining), with some few alias */
284 static const OPT_PAIR doit_choices[] = {
285     {"md2", D_MD2},
286     {"mdc2", D_MDC2},
287     {"md4", D_MD4},
288     {"md5", D_MD5},
289     {"hmac", D_HMAC},
290     {"sha1", D_SHA1},
291     {"sha256", D_SHA256},
292     {"sha512", D_SHA512},
293     {"whirlpool", D_WHIRLPOOL},
294     {"ripemd", D_RMD160},
295     {"rmd160", D_RMD160},
296     {"ripemd160", D_RMD160},
297     {"rc4", D_RC4},
298     {"des-cbc", D_CBC_DES},
299     {"des-ede3", D_EDE3_DES},
300     {"aes-128-cbc", D_CBC_128_AES},
301     {"aes-192-cbc", D_CBC_192_AES},
302     {"aes-256-cbc", D_CBC_256_AES},
303     {"camellia-128-cbc", D_CBC_128_CML},
304     {"camellia-192-cbc", D_CBC_192_CML},
305     {"camellia-256-cbc", D_CBC_256_CML},
306     {"rc2-cbc", D_CBC_RC2},
307     {"rc2", D_CBC_RC2},
308     {"rc5-cbc", D_CBC_RC5},
309     {"rc5", D_CBC_RC5},
310     {"idea-cbc", D_CBC_IDEA},
311     {"idea", D_CBC_IDEA},
312     {"seed-cbc", D_CBC_SEED},
313     {"seed", D_CBC_SEED},
314     {"bf-cbc", D_CBC_BF},
315     {"blowfish", D_CBC_BF},
316     {"bf", D_CBC_BF},
317     {"cast-cbc", D_CBC_CAST},
318     {"cast", D_CBC_CAST},
319     {"cast5", D_CBC_CAST},
320     {"ghash", D_GHASH},
321     {"rand", D_RAND}
322 };
323
324 static double results[ALGOR_NUM][SIZE_NUM];
325
326 enum { R_DSA_512, R_DSA_1024, R_DSA_2048, DSA_NUM };
327 static const OPT_PAIR dsa_choices[DSA_NUM] = {
328     {"dsa512", R_DSA_512},
329     {"dsa1024", R_DSA_1024},
330     {"dsa2048", R_DSA_2048}
331 };
332 static double dsa_results[DSA_NUM][2];  /* 2 ops: sign then verify */
333
334 enum {
335     R_RSA_512, R_RSA_1024, R_RSA_2048, R_RSA_3072, R_RSA_4096, R_RSA_7680,
336     R_RSA_15360, RSA_NUM
337 };
338 static const OPT_PAIR rsa_choices[RSA_NUM] = {
339     {"rsa512", R_RSA_512},
340     {"rsa1024", R_RSA_1024},
341     {"rsa2048", R_RSA_2048},
342     {"rsa3072", R_RSA_3072},
343     {"rsa4096", R_RSA_4096},
344     {"rsa7680", R_RSA_7680},
345     {"rsa15360", R_RSA_15360}
346 };
347
348 static double rsa_results[RSA_NUM][2];  /* 2 ops: sign then verify */
349
350 #ifndef OPENSSL_NO_DH
351 enum ff_params_t {
352     R_FFDH_2048, R_FFDH_3072, R_FFDH_4096, R_FFDH_6144, R_FFDH_8192, FFDH_NUM
353 };
354
355 static const OPT_PAIR ffdh_choices[FFDH_NUM] = {
356     {"ffdh2048", R_FFDH_2048},
357     {"ffdh3072", R_FFDH_3072},
358     {"ffdh4096", R_FFDH_4096},
359     {"ffdh6144", R_FFDH_6144},
360     {"ffdh8192", R_FFDH_8192},
361 };
362
363 static double ffdh_results[FFDH_NUM][1];  /* 1 op: derivation */
364 #endif /* OPENSSL_NO_DH */
365
366 enum ec_curves_t {
367     R_EC_P160, R_EC_P192, R_EC_P224, R_EC_P256, R_EC_P384, R_EC_P521,
368 #ifndef OPENSSL_NO_EC2M
369     R_EC_K163, R_EC_K233, R_EC_K283, R_EC_K409, R_EC_K571,
370     R_EC_B163, R_EC_B233, R_EC_B283, R_EC_B409, R_EC_B571,
371 #endif
372     R_EC_BRP256R1, R_EC_BRP256T1, R_EC_BRP384R1, R_EC_BRP384T1,
373     R_EC_BRP512R1, R_EC_BRP512T1, ECDSA_NUM
374 };
375 /* list of ecdsa curves */
376 static const OPT_PAIR ecdsa_choices[ECDSA_NUM] = {
377     {"ecdsap160", R_EC_P160},
378     {"ecdsap192", R_EC_P192},
379     {"ecdsap224", R_EC_P224},
380     {"ecdsap256", R_EC_P256},
381     {"ecdsap384", R_EC_P384},
382     {"ecdsap521", R_EC_P521},
383 #ifndef OPENSSL_NO_EC2M
384     {"ecdsak163", R_EC_K163},
385     {"ecdsak233", R_EC_K233},
386     {"ecdsak283", R_EC_K283},
387     {"ecdsak409", R_EC_K409},
388     {"ecdsak571", R_EC_K571},
389     {"ecdsab163", R_EC_B163},
390     {"ecdsab233", R_EC_B233},
391     {"ecdsab283", R_EC_B283},
392     {"ecdsab409", R_EC_B409},
393     {"ecdsab571", R_EC_B571},
394 #endif
395     {"ecdsabrp256r1", R_EC_BRP256R1},
396     {"ecdsabrp256t1", R_EC_BRP256T1},
397     {"ecdsabrp384r1", R_EC_BRP384R1},
398     {"ecdsabrp384t1", R_EC_BRP384T1},
399     {"ecdsabrp512r1", R_EC_BRP512R1},
400     {"ecdsabrp512t1", R_EC_BRP512T1}
401 };
402 enum { R_EC_X25519 = ECDSA_NUM, R_EC_X448, EC_NUM };
403 /* list of ecdh curves, extension of |ecdsa_choices| list above */
404 static const OPT_PAIR ecdh_choices[EC_NUM] = {
405     {"ecdhp160", R_EC_P160},
406     {"ecdhp192", R_EC_P192},
407     {"ecdhp224", R_EC_P224},
408     {"ecdhp256", R_EC_P256},
409     {"ecdhp384", R_EC_P384},
410     {"ecdhp521", R_EC_P521},
411 #ifndef OPENSSL_NO_EC2M
412     {"ecdhk163", R_EC_K163},
413     {"ecdhk233", R_EC_K233},
414     {"ecdhk283", R_EC_K283},
415     {"ecdhk409", R_EC_K409},
416     {"ecdhk571", R_EC_K571},
417     {"ecdhb163", R_EC_B163},
418     {"ecdhb233", R_EC_B233},
419     {"ecdhb283", R_EC_B283},
420     {"ecdhb409", R_EC_B409},
421     {"ecdhb571", R_EC_B571},
422 #endif
423     {"ecdhbrp256r1", R_EC_BRP256R1},
424     {"ecdhbrp256t1", R_EC_BRP256T1},
425     {"ecdhbrp384r1", R_EC_BRP384R1},
426     {"ecdhbrp384t1", R_EC_BRP384T1},
427     {"ecdhbrp512r1", R_EC_BRP512R1},
428     {"ecdhbrp512t1", R_EC_BRP512T1},
429     {"ecdhx25519", R_EC_X25519},
430     {"ecdhx448", R_EC_X448}
431 };
432
433 static double ecdh_results[EC_NUM][1];      /* 1 op: derivation */
434 static double ecdsa_results[ECDSA_NUM][2];  /* 2 ops: sign then verify */
435
436 enum { R_EC_Ed25519, R_EC_Ed448, EdDSA_NUM };
437 static const OPT_PAIR eddsa_choices[EdDSA_NUM] = {
438     {"ed25519", R_EC_Ed25519},
439     {"ed448", R_EC_Ed448}
440
441 };
442 static double eddsa_results[EdDSA_NUM][2];    /* 2 ops: sign then verify */
443
444 #ifndef OPENSSL_NO_SM2
445 enum { R_EC_CURVESM2, SM2_NUM };
446 static const OPT_PAIR sm2_choices[SM2_NUM] = {
447     {"curveSM2", R_EC_CURVESM2}
448 };
449 # define SM2_ID        "TLSv1.3+GM+Cipher+Suite"
450 # define SM2_ID_LEN    sizeof("TLSv1.3+GM+Cipher+Suite") - 1
451 static double sm2_results[SM2_NUM][2];    /* 2 ops: sign then verify */
452 #endif /* OPENSSL_NO_SM2 */
453
454 #define COND(unused_cond) (run && count < 0x7fffffff)
455 #define COUNT(d) (count)
456
457 typedef struct loopargs_st {
458     ASYNC_JOB *inprogress_job;
459     ASYNC_WAIT_CTX *wait_ctx;
460     unsigned char *buf;
461     unsigned char *buf2;
462     unsigned char *buf_malloc;
463     unsigned char *buf2_malloc;
464     unsigned char *key;
465     size_t buflen;
466     size_t sigsize;
467     EVP_PKEY_CTX *rsa_sign_ctx[RSA_NUM];
468     EVP_PKEY_CTX *rsa_verify_ctx[RSA_NUM];
469     EVP_PKEY_CTX *dsa_sign_ctx[DSA_NUM];
470     EVP_PKEY_CTX *dsa_verify_ctx[DSA_NUM];
471     EVP_PKEY_CTX *ecdsa_sign_ctx[ECDSA_NUM];
472     EVP_PKEY_CTX *ecdsa_verify_ctx[ECDSA_NUM];
473     EVP_PKEY_CTX *ecdh_ctx[EC_NUM];
474     EVP_MD_CTX *eddsa_ctx[EdDSA_NUM];
475     EVP_MD_CTX *eddsa_ctx2[EdDSA_NUM];
476 #ifndef OPENSSL_NO_SM2
477     EVP_MD_CTX *sm2_ctx[SM2_NUM];
478     EVP_MD_CTX *sm2_vfy_ctx[SM2_NUM];
479     EVP_PKEY *sm2_pkey[SM2_NUM];
480 #endif
481     unsigned char *secret_a;
482     unsigned char *secret_b;
483     size_t outlen[EC_NUM];
484 #ifndef OPENSSL_NO_DH
485     EVP_PKEY_CTX *ffdh_ctx[FFDH_NUM];
486     unsigned char *secret_ff_a;
487     unsigned char *secret_ff_b;
488 #endif
489     EVP_CIPHER_CTX *ctx;
490     EVP_MAC_CTX *mctx;
491 } loopargs_t;
492 static int run_benchmark(int async_jobs, int (*loop_function) (void *),
493                          loopargs_t * loopargs);
494
495 static unsigned int testnum;
496
497 /* Nb of iterations to do per algorithm and key-size */
498 static long c[ALGOR_NUM][SIZE_NUM];
499
500 static char *evp_mac_mdname = "md5";
501 static char *evp_hmac_name = NULL;
502 static const char *evp_md_name = NULL;
503 static char *evp_mac_ciphername = "aes-128-cbc";
504 static char *evp_cmac_name = NULL;
505
506 static int have_md(const char *name)
507 {
508     int ret = 0;
509     EVP_MD *md = NULL;
510
511     if (opt_md_silent(name, &md)) {
512         EVP_MD_CTX *ctx = EVP_MD_CTX_new();
513
514         if (ctx != NULL && EVP_DigestInit(ctx, md) > 0)
515             ret = 1;
516         EVP_MD_CTX_free(ctx);
517         EVP_MD_free(md);
518     }
519     return ret;
520 }
521
522 static int have_cipher(const char *name)
523 {
524     int ret = 0;
525     EVP_CIPHER *cipher = NULL;
526
527     if (opt_cipher_silent(name, &cipher)) {
528         EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
529
530         if (ctx != NULL
531             && EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, 1) > 0)
532             ret = 1;
533         EVP_CIPHER_CTX_free(ctx);
534         EVP_CIPHER_free(cipher);
535     }
536     return ret;
537 }
538
539 static int EVP_Digest_loop(const char *mdname, int algindex, void *args)
540 {
541     loopargs_t *tempargs = *(loopargs_t **) args;
542     unsigned char *buf = tempargs->buf;
543     unsigned char digest[EVP_MAX_MD_SIZE];
544     int count;
545     EVP_MD *md = NULL;
546
547     if (!opt_md_silent(mdname, &md))
548         return -1;
549     for (count = 0; COND(c[algindex][testnum]); count++) {
550         if (!EVP_Digest(buf, (size_t)lengths[testnum], digest, NULL, md,
551                         NULL)) {
552             count = -1;
553             break;
554         }
555     }
556     EVP_MD_free(md);
557     return count;
558 }
559
560 static int EVP_Digest_md_loop(void *args)
561 {
562     return EVP_Digest_loop(evp_md_name, D_EVP, args);
563 }
564
565 static int EVP_Digest_MD2_loop(void *args)
566 {
567     return EVP_Digest_loop("md2", D_MD2, args);
568 }
569
570 static int EVP_Digest_MDC2_loop(void *args)
571 {
572     return EVP_Digest_loop("mdc2", D_MDC2, args);
573 }
574
575 static int EVP_Digest_MD4_loop(void *args)
576 {
577     return EVP_Digest_loop("md4", D_MD4, args);
578 }
579
580 static int MD5_loop(void *args)
581 {
582     return EVP_Digest_loop("md5", D_MD5, args);
583 }
584
585 static int EVP_MAC_loop(int algindex, void *args)
586 {
587     loopargs_t *tempargs = *(loopargs_t **) args;
588     unsigned char *buf = tempargs->buf;
589     EVP_MAC_CTX *mctx = tempargs->mctx;
590     unsigned char mac[EVP_MAX_MD_SIZE];
591     int count;
592
593     for (count = 0; COND(c[algindex][testnum]); count++) {
594         size_t outl;
595
596         if (!EVP_MAC_init(mctx, NULL, 0, NULL)
597             || !EVP_MAC_update(mctx, buf, lengths[testnum])
598             || !EVP_MAC_final(mctx, mac, &outl, sizeof(mac)))
599             return -1;
600     }
601     return count;
602 }
603
604 static int HMAC_loop(void *args)
605 {
606     return EVP_MAC_loop(D_HMAC, args);
607 }
608
609 static int CMAC_loop(void *args)
610 {
611     return EVP_MAC_loop(D_EVP_CMAC, args);
612 }
613
614 static int SHA1_loop(void *args)
615 {
616     return EVP_Digest_loop("sha1", D_SHA1, args);
617 }
618
619 static int SHA256_loop(void *args)
620 {
621     return EVP_Digest_loop("sha256", D_SHA256, args);
622 }
623
624 static int SHA512_loop(void *args)
625 {
626     return EVP_Digest_loop("sha512", D_SHA512, args);
627 }
628
629 static int WHIRLPOOL_loop(void *args)
630 {
631     return EVP_Digest_loop("whirlpool", D_WHIRLPOOL, args);
632 }
633
634 static int EVP_Digest_RMD160_loop(void *args)
635 {
636     return EVP_Digest_loop("ripemd160", D_RMD160, args);
637 }
638
639 static int algindex;
640
641 static int EVP_Cipher_loop(void *args)
642 {
643     loopargs_t *tempargs = *(loopargs_t **) args;
644     unsigned char *buf = tempargs->buf;
645     int count;
646
647     if (tempargs->ctx == NULL)
648         return -1;
649     for (count = 0; COND(c[algindex][testnum]); count++)
650         if (EVP_Cipher(tempargs->ctx, buf, buf, (size_t)lengths[testnum]) <= 0)
651             return -1;
652     return count;
653 }
654
655 static int GHASH_loop(void *args)
656 {
657     loopargs_t *tempargs = *(loopargs_t **) args;
658     unsigned char *buf = tempargs->buf;
659     EVP_MAC_CTX *mctx = tempargs->mctx;
660     int count;
661
662     /* just do the update in the loop to be comparable with 1.1.1 */
663     for (count = 0; COND(c[D_GHASH][testnum]); count++) {
664         if (!EVP_MAC_update(mctx, buf, lengths[testnum]))
665             return -1;
666     }
667     return count;
668 }
669
670 #define MAX_BLOCK_SIZE 128
671
672 static unsigned char iv[2 * MAX_BLOCK_SIZE / 8];
673
674 static EVP_CIPHER_CTX *init_evp_cipher_ctx(const char *ciphername,
675                                            const unsigned char *key,
676                                            int keylen)
677 {
678     EVP_CIPHER_CTX *ctx = NULL;
679     EVP_CIPHER *cipher = NULL;
680
681     if (!opt_cipher_silent(ciphername, &cipher))
682         return NULL;
683
684     if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
685         goto end;
686
687     if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, 1)) {
688         EVP_CIPHER_CTX_free(ctx);
689         ctx = NULL;
690         goto end;
691     }
692
693     if (!EVP_CIPHER_CTX_set_key_length(ctx, keylen)) {
694         EVP_CIPHER_CTX_free(ctx);
695         ctx = NULL;
696         goto end;
697     }
698
699     if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, 1)) {
700         EVP_CIPHER_CTX_free(ctx);
701         ctx = NULL;
702         goto end;
703     }
704
705 end:
706     EVP_CIPHER_free(cipher);
707     return ctx;
708 }
709
710 static int RAND_bytes_loop(void *args)
711 {
712     loopargs_t *tempargs = *(loopargs_t **) args;
713     unsigned char *buf = tempargs->buf;
714     int count;
715
716     for (count = 0; COND(c[D_RAND][testnum]); count++)
717         RAND_bytes(buf, lengths[testnum]);
718     return count;
719 }
720
721 static int decrypt = 0;
722 static int EVP_Update_loop(void *args)
723 {
724     loopargs_t *tempargs = *(loopargs_t **) args;
725     unsigned char *buf = tempargs->buf;
726     EVP_CIPHER_CTX *ctx = tempargs->ctx;
727     int outl, count, rc;
728
729     if (decrypt) {
730         for (count = 0; COND(c[D_EVP][testnum]); count++) {
731             rc = EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
732             if (rc != 1) {
733                 /* reset iv in case of counter overflow */
734                 EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1);
735             }
736         }
737     } else {
738         for (count = 0; COND(c[D_EVP][testnum]); count++) {
739             rc = EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
740             if (rc != 1) {
741                 /* reset iv in case of counter overflow */
742                 EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1);
743             }
744         }
745     }
746     if (decrypt)
747         EVP_DecryptFinal_ex(ctx, buf, &outl);
748     else
749         EVP_EncryptFinal_ex(ctx, buf, &outl);
750     return count;
751 }
752
753 /*
754  * CCM does not support streaming. For the purpose of performance measurement,
755  * each message is encrypted using the same (key,iv)-pair. Do not use this
756  * code in your application.
757  */
758 static int EVP_Update_loop_ccm(void *args)
759 {
760     loopargs_t *tempargs = *(loopargs_t **) args;
761     unsigned char *buf = tempargs->buf;
762     EVP_CIPHER_CTX *ctx = tempargs->ctx;
763     int outl, count;
764     unsigned char tag[12];
765
766     if (decrypt) {
767         for (count = 0; COND(c[D_EVP][testnum]); count++) {
768             (void)EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, sizeof(tag),
769                                       tag);
770             /* reset iv */
771             (void)EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, iv);
772             /* counter is reset on every update */
773             (void)EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
774         }
775     } else {
776         for (count = 0; COND(c[D_EVP][testnum]); count++) {
777             /* restore iv length field */
778             (void)EVP_EncryptUpdate(ctx, NULL, &outl, NULL, lengths[testnum]);
779             /* counter is reset on every update */
780             (void)EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
781         }
782     }
783     if (decrypt)
784         (void)EVP_DecryptFinal_ex(ctx, buf, &outl);
785     else
786         (void)EVP_EncryptFinal_ex(ctx, buf, &outl);
787     return count;
788 }
789
790 /*
791  * To make AEAD benchmarking more relevant perform TLS-like operations,
792  * 13-byte AAD followed by payload. But don't use TLS-formatted AAD, as
793  * payload length is not actually limited by 16KB...
794  */
795 static int EVP_Update_loop_aead(void *args)
796 {
797     loopargs_t *tempargs = *(loopargs_t **) args;
798     unsigned char *buf = tempargs->buf;
799     EVP_CIPHER_CTX *ctx = tempargs->ctx;
800     int outl, count;
801     unsigned char aad[13] = { 0xcc };
802     unsigned char faketag[16] = { 0xcc };
803
804     if (decrypt) {
805         for (count = 0; COND(c[D_EVP][testnum]); count++) {
806             (void)EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, iv);
807             (void)EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
808                                       sizeof(faketag), faketag);
809             (void)EVP_DecryptUpdate(ctx, NULL, &outl, aad, sizeof(aad));
810             (void)EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
811             (void)EVP_DecryptFinal_ex(ctx, buf + outl, &outl);
812         }
813     } else {
814         for (count = 0; COND(c[D_EVP][testnum]); count++) {
815             (void)EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, iv);
816             (void)EVP_EncryptUpdate(ctx, NULL, &outl, aad, sizeof(aad));
817             (void)EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]);
818             (void)EVP_EncryptFinal_ex(ctx, buf + outl, &outl);
819         }
820     }
821     return count;
822 }
823
824 static long rsa_c[RSA_NUM][2];  /* # RSA iteration test */
825
826 static int RSA_sign_loop(void *args)
827 {
828     loopargs_t *tempargs = *(loopargs_t **) args;
829     unsigned char *buf = tempargs->buf;
830     unsigned char *buf2 = tempargs->buf2;
831     size_t *rsa_num = &tempargs->sigsize;
832     EVP_PKEY_CTX **rsa_sign_ctx = tempargs->rsa_sign_ctx;
833     int ret, count;
834
835     for (count = 0; COND(rsa_c[testnum][0]); count++) {
836         *rsa_num = tempargs->buflen;
837         ret = EVP_PKEY_sign(rsa_sign_ctx[testnum], buf2, rsa_num, buf, 36);
838         if (ret <= 0) {
839             BIO_printf(bio_err, "RSA sign failure\n");
840             ERR_print_errors(bio_err);
841             count = -1;
842             break;
843         }
844     }
845     return count;
846 }
847
848 static int RSA_verify_loop(void *args)
849 {
850     loopargs_t *tempargs = *(loopargs_t **) args;
851     unsigned char *buf = tempargs->buf;
852     unsigned char *buf2 = tempargs->buf2;
853     size_t rsa_num = tempargs->sigsize;
854     EVP_PKEY_CTX **rsa_verify_ctx = tempargs->rsa_verify_ctx;
855     int ret, count;
856
857     for (count = 0; COND(rsa_c[testnum][1]); count++) {
858         ret = EVP_PKEY_verify(rsa_verify_ctx[testnum], buf2, rsa_num, buf, 36);
859         if (ret <= 0) {
860             BIO_printf(bio_err, "RSA verify failure\n");
861             ERR_print_errors(bio_err);
862             count = -1;
863             break;
864         }
865     }
866     return count;
867 }
868
869 #ifndef OPENSSL_NO_DH
870 static long ffdh_c[FFDH_NUM][1];
871
872 static int FFDH_derive_key_loop(void *args)
873 {
874     loopargs_t *tempargs = *(loopargs_t **) args;
875     EVP_PKEY_CTX *ffdh_ctx = tempargs->ffdh_ctx[testnum];
876     unsigned char *derived_secret = tempargs->secret_ff_a;
877     size_t outlen = MAX_FFDH_SIZE;
878     int count;
879
880     for (count = 0; COND(ffdh_c[testnum][0]); count++)
881         EVP_PKEY_derive(ffdh_ctx, derived_secret, &outlen);
882     return count;
883 }
884 #endif /* OPENSSL_NO_DH */
885
886 static long dsa_c[DSA_NUM][2];
887 static int DSA_sign_loop(void *args)
888 {
889     loopargs_t *tempargs = *(loopargs_t **) args;
890     unsigned char *buf = tempargs->buf;
891     unsigned char *buf2 = tempargs->buf2;
892     size_t *dsa_num = &tempargs->sigsize;
893     EVP_PKEY_CTX **dsa_sign_ctx = tempargs->dsa_sign_ctx;
894     int ret, count;
895
896     for (count = 0; COND(dsa_c[testnum][0]); count++) {
897         *dsa_num = tempargs->buflen;
898         ret = EVP_PKEY_sign(dsa_sign_ctx[testnum], buf2, dsa_num, buf, 20);
899         if (ret <= 0) {
900             BIO_printf(bio_err, "DSA sign failure\n");
901             ERR_print_errors(bio_err);
902             count = -1;
903             break;
904         }
905     }
906     return count;
907 }
908
909 static int DSA_verify_loop(void *args)
910 {
911     loopargs_t *tempargs = *(loopargs_t **) args;
912     unsigned char *buf = tempargs->buf;
913     unsigned char *buf2 = tempargs->buf2;
914     size_t dsa_num = tempargs->sigsize;
915     EVP_PKEY_CTX **dsa_verify_ctx = tempargs->dsa_verify_ctx;
916     int ret, count;
917
918     for (count = 0; COND(dsa_c[testnum][1]); count++) {
919         ret = EVP_PKEY_verify(dsa_verify_ctx[testnum], buf2, dsa_num, buf, 20);
920         if (ret <= 0) {
921             BIO_printf(bio_err, "DSA verify failure\n");
922             ERR_print_errors(bio_err);
923             count = -1;
924             break;
925         }
926     }
927     return count;
928 }
929
930 static long ecdsa_c[ECDSA_NUM][2];
931 static int ECDSA_sign_loop(void *args)
932 {
933     loopargs_t *tempargs = *(loopargs_t **) args;
934     unsigned char *buf = tempargs->buf;
935     unsigned char *buf2 = tempargs->buf2;
936     size_t *ecdsa_num = &tempargs->sigsize;
937     EVP_PKEY_CTX **ecdsa_sign_ctx = tempargs->ecdsa_sign_ctx;
938     int ret, count;
939
940     for (count = 0; COND(ecdsa_c[testnum][0]); count++) {
941         *ecdsa_num = tempargs->buflen;
942         ret = EVP_PKEY_sign(ecdsa_sign_ctx[testnum], buf2, ecdsa_num, buf, 20);
943         if (ret <= 0) {
944             BIO_printf(bio_err, "ECDSA sign failure\n");
945             ERR_print_errors(bio_err);
946             count = -1;
947             break;
948         }
949     }
950     return count;
951 }
952
953 static int ECDSA_verify_loop(void *args)
954 {
955     loopargs_t *tempargs = *(loopargs_t **) args;
956     unsigned char *buf = tempargs->buf;
957     unsigned char *buf2 = tempargs->buf2;
958     size_t ecdsa_num = tempargs->sigsize;
959     EVP_PKEY_CTX **ecdsa_verify_ctx = tempargs->ecdsa_verify_ctx;
960     int ret, count;
961
962     for (count = 0; COND(ecdsa_c[testnum][1]); count++) {
963         ret = EVP_PKEY_verify(ecdsa_verify_ctx[testnum], buf2, ecdsa_num,
964                               buf, 20);
965         if (ret <= 0) {
966             BIO_printf(bio_err, "ECDSA verify failure\n");
967             ERR_print_errors(bio_err);
968             count = -1;
969             break;
970         }
971     }
972     return count;
973 }
974
975 /* ******************************************************************** */
976 static long ecdh_c[EC_NUM][1];
977
978 static int ECDH_EVP_derive_key_loop(void *args)
979 {
980     loopargs_t *tempargs = *(loopargs_t **) args;
981     EVP_PKEY_CTX *ctx = tempargs->ecdh_ctx[testnum];
982     unsigned char *derived_secret = tempargs->secret_a;
983     int count;
984     size_t *outlen = &(tempargs->outlen[testnum]);
985
986     for (count = 0; COND(ecdh_c[testnum][0]); count++)
987         EVP_PKEY_derive(ctx, derived_secret, outlen);
988
989     return count;
990 }
991
992 static long eddsa_c[EdDSA_NUM][2];
993 static int EdDSA_sign_loop(void *args)
994 {
995     loopargs_t *tempargs = *(loopargs_t **) args;
996     unsigned char *buf = tempargs->buf;
997     EVP_MD_CTX **edctx = tempargs->eddsa_ctx;
998     unsigned char *eddsasig = tempargs->buf2;
999     size_t *eddsasigsize = &tempargs->sigsize;
1000     int ret, count;
1001
1002     for (count = 0; COND(eddsa_c[testnum][0]); count++) {
1003         ret = EVP_DigestSign(edctx[testnum], eddsasig, eddsasigsize, buf, 20);
1004         if (ret == 0) {
1005             BIO_printf(bio_err, "EdDSA sign failure\n");
1006             ERR_print_errors(bio_err);
1007             count = -1;
1008             break;
1009         }
1010     }
1011     return count;
1012 }
1013
1014 static int EdDSA_verify_loop(void *args)
1015 {
1016     loopargs_t *tempargs = *(loopargs_t **) args;
1017     unsigned char *buf = tempargs->buf;
1018     EVP_MD_CTX **edctx = tempargs->eddsa_ctx2;
1019     unsigned char *eddsasig = tempargs->buf2;
1020     size_t eddsasigsize = tempargs->sigsize;
1021     int ret, count;
1022
1023     for (count = 0; COND(eddsa_c[testnum][1]); count++) {
1024         ret = EVP_DigestVerify(edctx[testnum], eddsasig, eddsasigsize, buf, 20);
1025         if (ret != 1) {
1026             BIO_printf(bio_err, "EdDSA verify failure\n");
1027             ERR_print_errors(bio_err);
1028             count = -1;
1029             break;
1030         }
1031     }
1032     return count;
1033 }
1034
1035 #ifndef OPENSSL_NO_SM2
1036 static long sm2_c[SM2_NUM][2];
1037 static int SM2_sign_loop(void *args)
1038 {
1039     loopargs_t *tempargs = *(loopargs_t **) args;
1040     unsigned char *buf = tempargs->buf;
1041     EVP_MD_CTX **sm2ctx = tempargs->sm2_ctx;
1042     unsigned char *sm2sig = tempargs->buf2;
1043     size_t sm2sigsize;
1044     int ret, count;
1045     EVP_PKEY **sm2_pkey = tempargs->sm2_pkey;
1046     const size_t max_size = EVP_PKEY_get_size(sm2_pkey[testnum]);
1047
1048     for (count = 0; COND(sm2_c[testnum][0]); count++) {
1049         sm2sigsize = max_size;
1050
1051         if (!EVP_DigestSignInit(sm2ctx[testnum], NULL, EVP_sm3(),
1052                                 NULL, sm2_pkey[testnum])) {
1053             BIO_printf(bio_err, "SM2 init sign failure\n");
1054             ERR_print_errors(bio_err);
1055             count = -1;
1056             break;
1057         }
1058         ret = EVP_DigestSign(sm2ctx[testnum], sm2sig, &sm2sigsize,
1059                              buf, 20);
1060         if (ret == 0) {
1061             BIO_printf(bio_err, "SM2 sign failure\n");
1062             ERR_print_errors(bio_err);
1063             count = -1;
1064             break;
1065         }
1066         /* update the latest returned size and always use the fixed buffer size */
1067         tempargs->sigsize = sm2sigsize;
1068     }
1069
1070     return count;
1071 }
1072
1073 static int SM2_verify_loop(void *args)
1074 {
1075     loopargs_t *tempargs = *(loopargs_t **) args;
1076     unsigned char *buf = tempargs->buf;
1077     EVP_MD_CTX **sm2ctx = tempargs->sm2_vfy_ctx;
1078     unsigned char *sm2sig = tempargs->buf2;
1079     size_t sm2sigsize = tempargs->sigsize;
1080     int ret, count;
1081     EVP_PKEY **sm2_pkey = tempargs->sm2_pkey;
1082
1083     for (count = 0; COND(sm2_c[testnum][1]); count++) {
1084         if (!EVP_DigestVerifyInit(sm2ctx[testnum], NULL, EVP_sm3(),
1085                                   NULL, sm2_pkey[testnum])) {
1086             BIO_printf(bio_err, "SM2 verify init failure\n");
1087             ERR_print_errors(bio_err);
1088             count = -1;
1089             break;
1090         }
1091         ret = EVP_DigestVerify(sm2ctx[testnum], sm2sig, sm2sigsize,
1092                                buf, 20);
1093         if (ret != 1) {
1094             BIO_printf(bio_err, "SM2 verify failure\n");
1095             ERR_print_errors(bio_err);
1096             count = -1;
1097             break;
1098         }
1099     }
1100     return count;
1101 }
1102 #endif                         /* OPENSSL_NO_SM2 */
1103
1104 static int run_benchmark(int async_jobs,
1105                          int (*loop_function) (void *), loopargs_t * loopargs)
1106 {
1107     int job_op_count = 0;
1108     int total_op_count = 0;
1109     int num_inprogress = 0;
1110     int error = 0, i = 0, ret = 0;
1111     OSSL_ASYNC_FD job_fd = 0;
1112     size_t num_job_fds = 0;
1113
1114     if (async_jobs == 0) {
1115         return loop_function((void *)&loopargs);
1116     }
1117
1118     for (i = 0; i < async_jobs && !error; i++) {
1119         loopargs_t *looparg_item = loopargs + i;
1120
1121         /* Copy pointer content (looparg_t item address) into async context */
1122         ret = ASYNC_start_job(&loopargs[i].inprogress_job, loopargs[i].wait_ctx,
1123                               &job_op_count, loop_function,
1124                               (void *)&looparg_item, sizeof(looparg_item));
1125         switch (ret) {
1126         case ASYNC_PAUSE:
1127             ++num_inprogress;
1128             break;
1129         case ASYNC_FINISH:
1130             if (job_op_count == -1) {
1131                 error = 1;
1132             } else {
1133                 total_op_count += job_op_count;
1134             }
1135             break;
1136         case ASYNC_NO_JOBS:
1137         case ASYNC_ERR:
1138             BIO_printf(bio_err, "Failure in the job\n");
1139             ERR_print_errors(bio_err);
1140             error = 1;
1141             break;
1142         }
1143     }
1144
1145     while (num_inprogress > 0) {
1146 #if defined(OPENSSL_SYS_WINDOWS)
1147         DWORD avail = 0;
1148 #elif defined(OPENSSL_SYS_UNIX)
1149         int select_result = 0;
1150         OSSL_ASYNC_FD max_fd = 0;
1151         fd_set waitfdset;
1152
1153         FD_ZERO(&waitfdset);
1154
1155         for (i = 0; i < async_jobs && num_inprogress > 0; i++) {
1156             if (loopargs[i].inprogress_job == NULL)
1157                 continue;
1158
1159             if (!ASYNC_WAIT_CTX_get_all_fds
1160                 (loopargs[i].wait_ctx, NULL, &num_job_fds)
1161                 || num_job_fds > 1) {
1162                 BIO_printf(bio_err, "Too many fds in ASYNC_WAIT_CTX\n");
1163                 ERR_print_errors(bio_err);
1164                 error = 1;
1165                 break;
1166             }
1167             ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd,
1168                                        &num_job_fds);
1169             FD_SET(job_fd, &waitfdset);
1170             if (job_fd > max_fd)
1171                 max_fd = job_fd;
1172         }
1173
1174         if (max_fd >= (OSSL_ASYNC_FD)FD_SETSIZE) {
1175             BIO_printf(bio_err,
1176                        "Error: max_fd (%d) must be smaller than FD_SETSIZE (%d). "
1177                        "Decrease the value of async_jobs\n",
1178                        max_fd, FD_SETSIZE);
1179             ERR_print_errors(bio_err);
1180             error = 1;
1181             break;
1182         }
1183
1184         select_result = select(max_fd + 1, &waitfdset, NULL, NULL, NULL);
1185         if (select_result == -1 && errno == EINTR)
1186             continue;
1187
1188         if (select_result == -1) {
1189             BIO_printf(bio_err, "Failure in the select\n");
1190             ERR_print_errors(bio_err);
1191             error = 1;
1192             break;
1193         }
1194
1195         if (select_result == 0)
1196             continue;
1197 #endif
1198
1199         for (i = 0; i < async_jobs; i++) {
1200             if (loopargs[i].inprogress_job == NULL)
1201                 continue;
1202
1203             if (!ASYNC_WAIT_CTX_get_all_fds
1204                 (loopargs[i].wait_ctx, NULL, &num_job_fds)
1205                 || num_job_fds > 1) {
1206                 BIO_printf(bio_err, "Too many fds in ASYNC_WAIT_CTX\n");
1207                 ERR_print_errors(bio_err);
1208                 error = 1;
1209                 break;
1210             }
1211             ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd,
1212                                        &num_job_fds);
1213
1214 #if defined(OPENSSL_SYS_UNIX)
1215             if (num_job_fds == 1 && !FD_ISSET(job_fd, &waitfdset))
1216                 continue;
1217 #elif defined(OPENSSL_SYS_WINDOWS)
1218             if (num_job_fds == 1
1219                 && !PeekNamedPipe(job_fd, NULL, 0, NULL, &avail, NULL)
1220                 && avail > 0)
1221                 continue;
1222 #endif
1223
1224             ret = ASYNC_start_job(&loopargs[i].inprogress_job,
1225                                   loopargs[i].wait_ctx, &job_op_count,
1226                                   loop_function, (void *)(loopargs + i),
1227                                   sizeof(loopargs_t));
1228             switch (ret) {
1229             case ASYNC_PAUSE:
1230                 break;
1231             case ASYNC_FINISH:
1232                 if (job_op_count == -1) {
1233                     error = 1;
1234                 } else {
1235                     total_op_count += job_op_count;
1236                 }
1237                 --num_inprogress;
1238                 loopargs[i].inprogress_job = NULL;
1239                 break;
1240             case ASYNC_NO_JOBS:
1241             case ASYNC_ERR:
1242                 --num_inprogress;
1243                 loopargs[i].inprogress_job = NULL;
1244                 BIO_printf(bio_err, "Failure in the job\n");
1245                 ERR_print_errors(bio_err);
1246                 error = 1;
1247                 break;
1248             }
1249         }
1250     }
1251
1252     return error ? -1 : total_op_count;
1253 }
1254
1255 typedef struct ec_curve_st {
1256     const char *name;
1257     unsigned int nid;
1258     unsigned int bits;
1259     size_t sigsize; /* only used for EdDSA curves */
1260 } EC_CURVE;
1261
1262 static EVP_PKEY *get_ecdsa(const EC_CURVE *curve)
1263 {
1264     EVP_PKEY_CTX *kctx = NULL;
1265     EVP_PKEY *key = NULL;
1266
1267     /* Ensure that the error queue is empty */
1268     if (ERR_peek_error()) {
1269         BIO_printf(bio_err,
1270                    "WARNING: the error queue contains previous unhandled errors.\n");
1271         ERR_print_errors(bio_err);
1272     }
1273
1274     /*
1275      * Let's try to create a ctx directly from the NID: this works for
1276      * curves like Curve25519 that are not implemented through the low
1277      * level EC interface.
1278      * If this fails we try creating a EVP_PKEY_EC generic param ctx,
1279      * then we set the curve by NID before deriving the actual keygen
1280      * ctx for that specific curve.
1281      */
1282     kctx = EVP_PKEY_CTX_new_id(curve->nid, NULL);
1283     if (kctx == NULL) {
1284         EVP_PKEY_CTX *pctx = NULL;
1285         EVP_PKEY *params = NULL;
1286         /*
1287          * If we reach this code EVP_PKEY_CTX_new_id() failed and a
1288          * "int_ctx_new:unsupported algorithm" error was added to the
1289          * error queue.
1290          * We remove it from the error queue as we are handling it.
1291          */
1292         unsigned long error = ERR_peek_error();
1293
1294         if (error == ERR_peek_last_error() /* oldest and latest errors match */
1295             /* check that the error origin matches */
1296             && ERR_GET_LIB(error) == ERR_LIB_EVP
1297             && (ERR_GET_REASON(error) == EVP_R_UNSUPPORTED_ALGORITHM
1298                 || ERR_GET_REASON(error) == ERR_R_UNSUPPORTED))
1299             ERR_get_error(); /* pop error from queue */
1300         if (ERR_peek_error()) {
1301             BIO_printf(bio_err,
1302                        "Unhandled error in the error queue during EC key setup.\n");
1303             ERR_print_errors(bio_err);
1304             return NULL;
1305         }
1306
1307         /* Create the context for parameter generation */
1308         if ((pctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL)) == NULL
1309             || EVP_PKEY_paramgen_init(pctx) <= 0
1310             || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx,
1311                                                       curve->nid) <= 0
1312             || EVP_PKEY_paramgen(pctx, &params) <= 0) {
1313             BIO_printf(bio_err, "EC params init failure.\n");
1314             ERR_print_errors(bio_err);
1315             EVP_PKEY_CTX_free(pctx);
1316             return NULL;
1317         }
1318         EVP_PKEY_CTX_free(pctx);
1319
1320         /* Create the context for the key generation */
1321         kctx = EVP_PKEY_CTX_new(params, NULL);
1322         EVP_PKEY_free(params);
1323     }
1324     if (kctx == NULL
1325         || EVP_PKEY_keygen_init(kctx) <= 0
1326         || EVP_PKEY_keygen(kctx, &key) <= 0) {
1327         BIO_printf(bio_err, "EC key generation failure.\n");
1328         ERR_print_errors(bio_err);
1329         key = NULL;
1330     }
1331     EVP_PKEY_CTX_free(kctx);
1332     return key;
1333 }
1334
1335 #define stop_it(do_it, test_num)\
1336     memset(do_it + test_num, 0, OSSL_NELEM(do_it) - test_num);
1337
1338 int speed_main(int argc, char **argv)
1339 {
1340     ENGINE *e = NULL;
1341     loopargs_t *loopargs = NULL;
1342     const char *prog;
1343     const char *engine_id = NULL;
1344     EVP_CIPHER *evp_cipher = NULL;
1345     EVP_MAC *mac = NULL;
1346     double d = 0.0;
1347     OPTION_CHOICE o;
1348     int async_init = 0, multiblock = 0, pr_header = 0;
1349     uint8_t doit[ALGOR_NUM] = { 0 };
1350     int ret = 1, misalign = 0, lengths_single = 0, aead = 0;
1351     long count = 0;
1352     unsigned int size_num = SIZE_NUM;
1353     unsigned int i, k, loopargs_len = 0, async_jobs = 0;
1354     int keylen;
1355     int buflen;
1356     BIGNUM *bn = NULL;
1357     EVP_PKEY_CTX *genctx = NULL;
1358 #ifndef NO_FORK
1359     int multi = 0;
1360 #endif
1361     long op_count = 1;
1362     openssl_speed_sec_t seconds = { SECONDS, RSA_SECONDS, DSA_SECONDS,
1363                                     ECDSA_SECONDS, ECDH_SECONDS,
1364                                     EdDSA_SECONDS, SM2_SECONDS,
1365                                     FFDH_SECONDS };
1366
1367     static const unsigned char key32[32] = {
1368         0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
1369         0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12,
1370         0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34,
1371         0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56
1372     };
1373     static const unsigned char deskey[] = {
1374         0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, /* key1 */
1375         0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, /* key2 */
1376         0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34  /* key3 */
1377     };
1378     static const struct {
1379         const unsigned char *data;
1380         unsigned int length;
1381         unsigned int bits;
1382     } rsa_keys[] = {
1383         {   test512,   sizeof(test512),   512 },
1384         {  test1024,  sizeof(test1024),  1024 },
1385         {  test2048,  sizeof(test2048),  2048 },
1386         {  test3072,  sizeof(test3072),  3072 },
1387         {  test4096,  sizeof(test4096),  4096 },
1388         {  test7680,  sizeof(test7680),  7680 },
1389         { test15360, sizeof(test15360), 15360 }
1390     };
1391     uint8_t rsa_doit[RSA_NUM] = { 0 };
1392     int primes = RSA_DEFAULT_PRIME_NUM;
1393 #ifndef OPENSSL_NO_DH
1394     typedef struct ffdh_params_st {
1395         const char *name;
1396         unsigned int nid;
1397         unsigned int bits;
1398     } FFDH_PARAMS;
1399
1400     static const FFDH_PARAMS ffdh_params[FFDH_NUM] = {
1401         {"ffdh2048", NID_ffdhe2048, 2048},
1402         {"ffdh3072", NID_ffdhe3072, 3072},
1403         {"ffdh4096", NID_ffdhe4096, 4096},
1404         {"ffdh6144", NID_ffdhe6144, 6144},
1405         {"ffdh8192", NID_ffdhe8192, 8192}
1406     };
1407     uint8_t ffdh_doit[FFDH_NUM] = { 0 };
1408
1409 #endif /* OPENSSL_NO_DH */
1410     static const unsigned int dsa_bits[DSA_NUM] = { 512, 1024, 2048 };
1411     uint8_t dsa_doit[DSA_NUM] = { 0 };
1412     /*
1413      * We only test over the following curves as they are representative, To
1414      * add tests over more curves, simply add the curve NID and curve name to
1415      * the following arrays and increase the |ecdh_choices| and |ecdsa_choices|
1416      * lists accordingly.
1417      */
1418     static const EC_CURVE ec_curves[EC_NUM] = {
1419         /* Prime Curves */
1420         {"secp160r1", NID_secp160r1, 160},
1421         {"nistp192", NID_X9_62_prime192v1, 192},
1422         {"nistp224", NID_secp224r1, 224},
1423         {"nistp256", NID_X9_62_prime256v1, 256},
1424         {"nistp384", NID_secp384r1, 384},
1425         {"nistp521", NID_secp521r1, 521},
1426 #ifndef OPENSSL_NO_EC2M
1427         /* Binary Curves */
1428         {"nistk163", NID_sect163k1, 163},
1429         {"nistk233", NID_sect233k1, 233},
1430         {"nistk283", NID_sect283k1, 283},
1431         {"nistk409", NID_sect409k1, 409},
1432         {"nistk571", NID_sect571k1, 571},
1433         {"nistb163", NID_sect163r2, 163},
1434         {"nistb233", NID_sect233r1, 233},
1435         {"nistb283", NID_sect283r1, 283},
1436         {"nistb409", NID_sect409r1, 409},
1437         {"nistb571", NID_sect571r1, 571},
1438 #endif
1439         {"brainpoolP256r1", NID_brainpoolP256r1, 256},
1440         {"brainpoolP256t1", NID_brainpoolP256t1, 256},
1441         {"brainpoolP384r1", NID_brainpoolP384r1, 384},
1442         {"brainpoolP384t1", NID_brainpoolP384t1, 384},
1443         {"brainpoolP512r1", NID_brainpoolP512r1, 512},
1444         {"brainpoolP512t1", NID_brainpoolP512t1, 512},
1445         /* Other and ECDH only ones */
1446         {"X25519", NID_X25519, 253},
1447         {"X448", NID_X448, 448}
1448     };
1449     static const EC_CURVE ed_curves[EdDSA_NUM] = {
1450         /* EdDSA */
1451         {"Ed25519", NID_ED25519, 253, 64},
1452         {"Ed448", NID_ED448, 456, 114}
1453     };
1454 #ifndef OPENSSL_NO_SM2
1455     static const EC_CURVE sm2_curves[SM2_NUM] = {
1456         /* SM2 */
1457         {"CurveSM2", NID_sm2, 256}
1458     };
1459     uint8_t sm2_doit[SM2_NUM] = { 0 };
1460 #endif
1461     uint8_t ecdsa_doit[ECDSA_NUM] = { 0 };
1462     uint8_t ecdh_doit[EC_NUM] = { 0 };
1463     uint8_t eddsa_doit[EdDSA_NUM] = { 0 };
1464
1465     /* checks declarated curves against choices list. */
1466     OPENSSL_assert(ed_curves[EdDSA_NUM - 1].nid == NID_ED448);
1467     OPENSSL_assert(strcmp(eddsa_choices[EdDSA_NUM - 1].name, "ed448") == 0);
1468
1469     OPENSSL_assert(ec_curves[EC_NUM - 1].nid == NID_X448);
1470     OPENSSL_assert(strcmp(ecdh_choices[EC_NUM - 1].name, "ecdhx448") == 0);
1471
1472     OPENSSL_assert(ec_curves[ECDSA_NUM - 1].nid == NID_brainpoolP512t1);
1473     OPENSSL_assert(strcmp(ecdsa_choices[ECDSA_NUM - 1].name, "ecdsabrp512t1") == 0);
1474
1475 #ifndef OPENSSL_NO_SM2
1476     OPENSSL_assert(sm2_curves[SM2_NUM - 1].nid == NID_sm2);
1477     OPENSSL_assert(strcmp(sm2_choices[SM2_NUM - 1].name, "curveSM2") == 0);
1478 #endif
1479
1480     prog = opt_init(argc, argv, speed_options);
1481     while ((o = opt_next()) != OPT_EOF) {
1482         switch (o) {
1483         case OPT_EOF:
1484         case OPT_ERR:
1485  opterr:
1486             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
1487             goto end;
1488         case OPT_HELP:
1489             opt_help(speed_options);
1490             ret = 0;
1491             goto end;
1492         case OPT_ELAPSED:
1493             usertime = 0;
1494             break;
1495         case OPT_EVP:
1496             if (doit[D_EVP]) {
1497                 BIO_printf(bio_err, "%s: -evp option cannot be used more than once\n", prog);
1498                 goto opterr;
1499             }
1500             ERR_set_mark();
1501             if (!opt_cipher_silent(opt_arg(), &evp_cipher)) {
1502                 if (have_md(opt_arg()))
1503                     evp_md_name = opt_arg();
1504             }
1505             if (evp_cipher == NULL && evp_md_name == NULL) {
1506                 ERR_clear_last_mark();
1507                 BIO_printf(bio_err,
1508                            "%s: %s is an unknown cipher or digest\n",
1509                            prog, opt_arg());
1510                 goto end;
1511             }
1512             ERR_pop_to_mark();
1513             doit[D_EVP] = 1;
1514             break;
1515         case OPT_HMAC:
1516             if (!have_md(opt_arg())) {
1517                 BIO_printf(bio_err, "%s: %s is an unknown digest\n",
1518                            prog, opt_arg());
1519                 goto end;
1520             }
1521             evp_mac_mdname = opt_arg();
1522             doit[D_HMAC] = 1;
1523             break;
1524         case OPT_CMAC:
1525             if (!have_cipher(opt_arg())) {
1526                 BIO_printf(bio_err, "%s: %s is an unknown cipher\n",
1527                            prog, opt_arg());
1528                 goto end;
1529             }
1530             evp_mac_ciphername = opt_arg();
1531             doit[D_EVP_CMAC] = 1;
1532             break;
1533         case OPT_DECRYPT:
1534             decrypt = 1;
1535             break;
1536         case OPT_ENGINE:
1537             /*
1538              * In a forked execution, an engine might need to be
1539              * initialised by each child process, not by the parent.
1540              * So store the name here and run setup_engine() later on.
1541              */
1542             engine_id = opt_arg();
1543             break;
1544         case OPT_MULTI:
1545 #ifndef NO_FORK
1546             multi = atoi(opt_arg());
1547             if ((size_t)multi >= SIZE_MAX / sizeof(int)) {
1548                 BIO_printf(bio_err, "%s: multi argument too large\n", prog);
1549                 return 0;
1550             }
1551 #endif
1552             break;
1553         case OPT_ASYNCJOBS:
1554 #ifndef OPENSSL_NO_ASYNC
1555             async_jobs = atoi(opt_arg());
1556             if (!ASYNC_is_capable()) {
1557                 BIO_printf(bio_err,
1558                            "%s: async_jobs specified but async not supported\n",
1559                            prog);
1560                 goto opterr;
1561             }
1562             if (async_jobs > 99999) {
1563                 BIO_printf(bio_err, "%s: too many async_jobs\n", prog);
1564                 goto opterr;
1565             }
1566 #endif
1567             break;
1568         case OPT_MISALIGN:
1569             misalign = opt_int_arg();
1570             if (misalign > MISALIGN) {
1571                 BIO_printf(bio_err,
1572                            "%s: Maximum offset is %d\n", prog, MISALIGN);
1573                 goto opterr;
1574             }
1575             break;
1576         case OPT_MR:
1577             mr = 1;
1578             break;
1579         case OPT_MB:
1580             multiblock = 1;
1581 #ifdef OPENSSL_NO_MULTIBLOCK
1582             BIO_printf(bio_err,
1583                        "%s: -mb specified but multi-block support is disabled\n",
1584                        prog);
1585             goto end;
1586 #endif
1587             break;
1588         case OPT_R_CASES:
1589             if (!opt_rand(o))
1590                 goto end;
1591             break;
1592         case OPT_PROV_CASES:
1593             if (!opt_provider(o))
1594                 goto end;
1595             break;
1596         case OPT_PRIMES:
1597             primes = opt_int_arg();
1598             break;
1599         case OPT_SECONDS:
1600             seconds.sym = seconds.rsa = seconds.dsa = seconds.ecdsa
1601                         = seconds.ecdh = seconds.eddsa
1602                         = seconds.sm2 = seconds.ffdh = atoi(opt_arg());
1603             break;
1604         case OPT_BYTES:
1605             lengths_single = atoi(opt_arg());
1606             lengths = &lengths_single;
1607             size_num = 1;
1608             break;
1609         case OPT_AEAD:
1610             aead = 1;
1611             break;
1612         }
1613     }
1614
1615     /* Remaining arguments are algorithms. */
1616     argc = opt_num_rest();
1617     argv = opt_rest();
1618
1619     if (!app_RAND_load())
1620         goto end;
1621
1622     for (; *argv; argv++) {
1623         const char *algo = *argv;
1624
1625         if (opt_found(algo, doit_choices, &i)) {
1626             doit[i] = 1;
1627             continue;
1628         }
1629         if (strcmp(algo, "des") == 0) {
1630             doit[D_CBC_DES] = doit[D_EDE3_DES] = 1;
1631             continue;
1632         }
1633         if (strcmp(algo, "sha") == 0) {
1634             doit[D_SHA1] = doit[D_SHA256] = doit[D_SHA512] = 1;
1635             continue;
1636         }
1637 #ifndef OPENSSL_NO_DEPRECATED_3_0
1638         if (strcmp(algo, "openssl") == 0) /* just for compatibility */
1639             continue;
1640 #endif
1641         if (HAS_PREFIX(algo, "rsa")) {
1642             if (algo[sizeof("rsa") - 1] == '\0') {
1643                 memset(rsa_doit, 1, sizeof(rsa_doit));
1644                 continue;
1645             }
1646             if (opt_found(algo, rsa_choices, &i)) {
1647                 rsa_doit[i] = 1;
1648                 continue;
1649             }
1650         }
1651 #ifndef OPENSSL_NO_DH
1652         if (HAS_PREFIX(algo, "ffdh")) {
1653             if (algo[sizeof("ffdh") - 1] == '\0') {
1654                 memset(ffdh_doit, 1, sizeof(ffdh_doit));
1655                 continue;
1656             }
1657             if (opt_found(algo, ffdh_choices, &i)) {
1658                 ffdh_doit[i] = 2;
1659                 continue;
1660             }
1661         }
1662 #endif
1663         if (HAS_PREFIX(algo, "dsa")) {
1664             if (algo[sizeof("dsa") - 1] == '\0') {
1665                 memset(dsa_doit, 1, sizeof(dsa_doit));
1666                 continue;
1667             }
1668             if (opt_found(algo, dsa_choices, &i)) {
1669                 dsa_doit[i] = 2;
1670                 continue;
1671             }
1672         }
1673         if (strcmp(algo, "aes") == 0) {
1674             doit[D_CBC_128_AES] = doit[D_CBC_192_AES] = doit[D_CBC_256_AES] = 1;
1675             continue;
1676         }
1677         if (strcmp(algo, "camellia") == 0) {
1678             doit[D_CBC_128_CML] = doit[D_CBC_192_CML] = doit[D_CBC_256_CML] = 1;
1679             continue;
1680         }
1681         if (HAS_PREFIX(algo, "ecdsa")) {
1682             if (algo[sizeof("ecdsa") - 1] == '\0') {
1683                 memset(ecdsa_doit, 1, sizeof(ecdsa_doit));
1684                 continue;
1685             }
1686             if (opt_found(algo, ecdsa_choices, &i)) {
1687                 ecdsa_doit[i] = 2;
1688                 continue;
1689             }
1690         }
1691         if (HAS_PREFIX(algo, "ecdh")) {
1692             if (algo[sizeof("ecdh") - 1] == '\0') {
1693                 memset(ecdh_doit, 1, sizeof(ecdh_doit));
1694                 continue;
1695             }
1696             if (opt_found(algo, ecdh_choices, &i)) {
1697                 ecdh_doit[i] = 2;
1698                 continue;
1699             }
1700         }
1701         if (strcmp(algo, "eddsa") == 0) {
1702             memset(eddsa_doit, 1, sizeof(eddsa_doit));
1703             continue;
1704         }
1705         if (opt_found(algo, eddsa_choices, &i)) {
1706             eddsa_doit[i] = 2;
1707             continue;
1708         }
1709 #ifndef OPENSSL_NO_SM2
1710         if (strcmp(algo, "sm2") == 0) {
1711             memset(sm2_doit, 1, sizeof(sm2_doit));
1712             continue;
1713         }
1714         if (opt_found(algo, sm2_choices, &i)) {
1715             sm2_doit[i] = 2;
1716             continue;
1717         }
1718 #endif
1719         BIO_printf(bio_err, "%s: Unknown algorithm %s\n", prog, algo);
1720         goto end;
1721     }
1722
1723     /* Sanity checks */
1724     if (aead) {
1725         if (evp_cipher == NULL) {
1726             BIO_printf(bio_err, "-aead can be used only with an AEAD cipher\n");
1727             goto end;
1728         } else if (!(EVP_CIPHER_get_flags(evp_cipher) &
1729                      EVP_CIPH_FLAG_AEAD_CIPHER)) {
1730             BIO_printf(bio_err, "%s is not an AEAD cipher\n",
1731                        EVP_CIPHER_get0_name(evp_cipher));
1732             goto end;
1733         }
1734     }
1735     if (multiblock) {
1736         if (evp_cipher == NULL) {
1737             BIO_printf(bio_err, "-mb can be used only with a multi-block"
1738                                 " capable cipher\n");
1739             goto end;
1740         } else if (!(EVP_CIPHER_get_flags(evp_cipher) &
1741                      EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)) {
1742             BIO_printf(bio_err, "%s is not a multi-block capable\n",
1743                        EVP_CIPHER_get0_name(evp_cipher));
1744             goto end;
1745         } else if (async_jobs > 0) {
1746             BIO_printf(bio_err, "Async mode is not supported with -mb");
1747             goto end;
1748         }
1749     }
1750
1751     /* Initialize the job pool if async mode is enabled */
1752     if (async_jobs > 0) {
1753         async_init = ASYNC_init_thread(async_jobs, async_jobs);
1754         if (!async_init) {
1755             BIO_printf(bio_err, "Error creating the ASYNC job pool\n");
1756             goto end;
1757         }
1758     }
1759
1760     loopargs_len = (async_jobs == 0 ? 1 : async_jobs);
1761     loopargs =
1762         app_malloc(loopargs_len * sizeof(loopargs_t), "array of loopargs");
1763     memset(loopargs, 0, loopargs_len * sizeof(loopargs_t));
1764
1765     for (i = 0; i < loopargs_len; i++) {
1766         if (async_jobs > 0) {
1767             loopargs[i].wait_ctx = ASYNC_WAIT_CTX_new();
1768             if (loopargs[i].wait_ctx == NULL) {
1769                 BIO_printf(bio_err, "Error creating the ASYNC_WAIT_CTX\n");
1770                 goto end;
1771             }
1772         }
1773
1774         buflen = lengths[size_num - 1];
1775         if (buflen < 36)    /* size of random vector in RSA benchmark */
1776             buflen = 36;
1777         buflen += MAX_MISALIGNMENT + 1;
1778         loopargs[i].buf_malloc = app_malloc(buflen, "input buffer");
1779         loopargs[i].buf2_malloc = app_malloc(buflen, "input buffer");
1780         memset(loopargs[i].buf_malloc, 0, buflen);
1781         memset(loopargs[i].buf2_malloc, 0, buflen);
1782
1783         /* Align the start of buffers on a 64 byte boundary */
1784         loopargs[i].buf = loopargs[i].buf_malloc + misalign;
1785         loopargs[i].buf2 = loopargs[i].buf2_malloc + misalign;
1786         loopargs[i].buflen = buflen - misalign;
1787         loopargs[i].sigsize = buflen - misalign;
1788         loopargs[i].secret_a = app_malloc(MAX_ECDH_SIZE, "ECDH secret a");
1789         loopargs[i].secret_b = app_malloc(MAX_ECDH_SIZE, "ECDH secret b");
1790 #ifndef OPENSSL_NO_DH
1791         loopargs[i].secret_ff_a = app_malloc(MAX_FFDH_SIZE, "FFDH secret a");
1792         loopargs[i].secret_ff_b = app_malloc(MAX_FFDH_SIZE, "FFDH secret b");
1793 #endif
1794     }
1795
1796 #ifndef NO_FORK
1797     if (multi && do_multi(multi, size_num))
1798         goto show_res;
1799 #endif
1800
1801     /* Initialize the engine after the fork */
1802     e = setup_engine(engine_id, 0);
1803
1804     /* No parameters; turn on everything. */
1805     if (argc == 0 && !doit[D_EVP] && !doit[D_HMAC] && !doit[D_EVP_CMAC]) {
1806         memset(doit, 1, sizeof(doit));
1807         doit[D_EVP] = doit[D_EVP_CMAC] = 0;
1808         ERR_set_mark();
1809         for (i = D_MD2; i <= D_WHIRLPOOL; i++) {
1810             if (!have_md(names[i]))
1811                 doit[i] = 0;
1812         }
1813         for (i = D_CBC_DES; i <= D_CBC_256_CML; i++) {
1814             if (!have_cipher(names[i]))
1815                 doit[i] = 0;
1816         }
1817         if ((mac = EVP_MAC_fetch(app_get0_libctx(), "GMAC",
1818                                  app_get0_propq())) != NULL) {
1819             EVP_MAC_free(mac);
1820             mac = NULL;
1821         } else {
1822             doit[D_GHASH] = 0;
1823         }
1824         if ((mac = EVP_MAC_fetch(app_get0_libctx(), "HMAC",
1825                                  app_get0_propq())) != NULL) {
1826             EVP_MAC_free(mac);
1827             mac = NULL;
1828         } else {
1829             doit[D_HMAC] = 0;
1830         }
1831         ERR_pop_to_mark();
1832         memset(rsa_doit, 1, sizeof(rsa_doit));
1833 #ifndef OPENSSL_NO_DH
1834         memset(ffdh_doit, 1, sizeof(ffdh_doit));
1835 #endif
1836         memset(dsa_doit, 1, sizeof(dsa_doit));
1837         memset(ecdsa_doit, 1, sizeof(ecdsa_doit));
1838         memset(ecdh_doit, 1, sizeof(ecdh_doit));
1839         memset(eddsa_doit, 1, sizeof(eddsa_doit));
1840 #ifndef OPENSSL_NO_SM2
1841         memset(sm2_doit, 1, sizeof(sm2_doit));
1842 #endif
1843     }
1844     for (i = 0; i < ALGOR_NUM; i++)
1845         if (doit[i])
1846             pr_header++;
1847
1848     if (usertime == 0 && !mr)
1849         BIO_printf(bio_err,
1850                    "You have chosen to measure elapsed time "
1851                    "instead of user CPU time.\n");
1852
1853 #if SIGALRM > 0
1854     signal(SIGALRM, alarmed);
1855 #endif
1856
1857     if (doit[D_MD2]) {
1858         for (testnum = 0; testnum < size_num; testnum++) {
1859             print_message(names[D_MD2], c[D_MD2][testnum], lengths[testnum],
1860                           seconds.sym);
1861             Time_F(START);
1862             count = run_benchmark(async_jobs, EVP_Digest_MD2_loop, loopargs);
1863             d = Time_F(STOP);
1864             print_result(D_MD2, testnum, count, d);
1865             if (count < 0)
1866                 break;
1867         }
1868     }
1869
1870     if (doit[D_MDC2]) {
1871         for (testnum = 0; testnum < size_num; testnum++) {
1872             print_message(names[D_MDC2], c[D_MDC2][testnum], lengths[testnum],
1873                           seconds.sym);
1874             Time_F(START);
1875             count = run_benchmark(async_jobs, EVP_Digest_MDC2_loop, loopargs);
1876             d = Time_F(STOP);
1877             print_result(D_MDC2, testnum, count, d);
1878             if (count < 0)
1879                 break;
1880         }
1881     }
1882
1883     if (doit[D_MD4]) {
1884         for (testnum = 0; testnum < size_num; testnum++) {
1885             print_message(names[D_MD4], c[D_MD4][testnum], lengths[testnum],
1886                           seconds.sym);
1887             Time_F(START);
1888             count = run_benchmark(async_jobs, EVP_Digest_MD4_loop, loopargs);
1889             d = Time_F(STOP);
1890             print_result(D_MD4, testnum, count, d);
1891             if (count < 0)
1892                 break;
1893         }
1894     }
1895
1896     if (doit[D_MD5]) {
1897         for (testnum = 0; testnum < size_num; testnum++) {
1898             print_message(names[D_MD5], c[D_MD5][testnum], lengths[testnum],
1899                           seconds.sym);
1900             Time_F(START);
1901             count = run_benchmark(async_jobs, MD5_loop, loopargs);
1902             d = Time_F(STOP);
1903             print_result(D_MD5, testnum, count, d);
1904             if (count < 0)
1905                 break;
1906         }
1907     }
1908
1909     if (doit[D_SHA1]) {
1910         for (testnum = 0; testnum < size_num; testnum++) {
1911             print_message(names[D_SHA1], c[D_SHA1][testnum], lengths[testnum],
1912                           seconds.sym);
1913             Time_F(START);
1914             count = run_benchmark(async_jobs, SHA1_loop, loopargs);
1915             d = Time_F(STOP);
1916             print_result(D_SHA1, testnum, count, d);
1917             if (count < 0)
1918                 break;
1919         }
1920     }
1921
1922     if (doit[D_SHA256]) {
1923         for (testnum = 0; testnum < size_num; testnum++) {
1924             print_message(names[D_SHA256], c[D_SHA256][testnum],
1925                           lengths[testnum], seconds.sym);
1926             Time_F(START);
1927             count = run_benchmark(async_jobs, SHA256_loop, loopargs);
1928             d = Time_F(STOP);
1929             print_result(D_SHA256, testnum, count, d);
1930             if (count < 0)
1931                 break;
1932         }
1933     }
1934
1935     if (doit[D_SHA512]) {
1936         for (testnum = 0; testnum < size_num; testnum++) {
1937             print_message(names[D_SHA512], c[D_SHA512][testnum],
1938                           lengths[testnum], seconds.sym);
1939             Time_F(START);
1940             count = run_benchmark(async_jobs, SHA512_loop, loopargs);
1941             d = Time_F(STOP);
1942             print_result(D_SHA512, testnum, count, d);
1943             if (count < 0)
1944                 break;
1945         }
1946     }
1947
1948     if (doit[D_WHIRLPOOL]) {
1949         for (testnum = 0; testnum < size_num; testnum++) {
1950             print_message(names[D_WHIRLPOOL], c[D_WHIRLPOOL][testnum],
1951                           lengths[testnum], seconds.sym);
1952             Time_F(START);
1953             count = run_benchmark(async_jobs, WHIRLPOOL_loop, loopargs);
1954             d = Time_F(STOP);
1955             print_result(D_WHIRLPOOL, testnum, count, d);
1956             if (count < 0)
1957                 break;
1958         }
1959     }
1960
1961     if (doit[D_RMD160]) {
1962         for (testnum = 0; testnum < size_num; testnum++) {
1963             print_message(names[D_RMD160], c[D_RMD160][testnum],
1964                           lengths[testnum], seconds.sym);
1965             Time_F(START);
1966             count = run_benchmark(async_jobs, EVP_Digest_RMD160_loop, loopargs);
1967             d = Time_F(STOP);
1968             print_result(D_RMD160, testnum, count, d);
1969             if (count < 0)
1970                 break;
1971         }
1972     }
1973
1974     if (doit[D_HMAC]) {
1975         static const char hmac_key[] = "This is a key...";
1976         int len = strlen(hmac_key);
1977         OSSL_PARAM params[3];
1978
1979         mac = EVP_MAC_fetch(app_get0_libctx(), "HMAC", app_get0_propq());
1980         if (mac == NULL || evp_mac_mdname == NULL)
1981             goto end;
1982
1983         evp_hmac_name = app_malloc(sizeof("hmac()") + strlen(evp_mac_mdname),
1984                                    "HMAC name");
1985         sprintf(evp_hmac_name, "hmac(%s)", evp_mac_mdname);
1986         names[D_HMAC] = evp_hmac_name;
1987
1988         params[0] =
1989             OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
1990                                              evp_mac_mdname, 0);
1991         params[1] =
1992             OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
1993                                               (char *)hmac_key, len);
1994         params[2] = OSSL_PARAM_construct_end();
1995
1996         for (i = 0; i < loopargs_len; i++) {
1997             loopargs[i].mctx = EVP_MAC_CTX_new(mac);
1998             if (loopargs[i].mctx == NULL)
1999                 goto end;
2000
2001             if (!EVP_MAC_CTX_set_params(loopargs[i].mctx, params))
2002                 goto end;
2003         }
2004         for (testnum = 0; testnum < size_num; testnum++) {
2005             print_message(names[D_HMAC], c[D_HMAC][testnum], lengths[testnum],
2006                           seconds.sym);
2007             Time_F(START);
2008             count = run_benchmark(async_jobs, HMAC_loop, loopargs);
2009             d = Time_F(STOP);
2010             print_result(D_HMAC, testnum, count, d);
2011             if (count < 0)
2012                 break;
2013         }
2014         for (i = 0; i < loopargs_len; i++)
2015             EVP_MAC_CTX_free(loopargs[i].mctx);
2016         EVP_MAC_free(mac);
2017         mac = NULL;
2018     }
2019
2020     if (doit[D_CBC_DES]) {
2021         int st = 1;
2022
2023         for (i = 0; st && i < loopargs_len; i++) {
2024             loopargs[i].ctx = init_evp_cipher_ctx("des-cbc", deskey,
2025                                                   sizeof(deskey) / 3);
2026             st = loopargs[i].ctx != NULL;
2027         }
2028         algindex = D_CBC_DES;
2029         for (testnum = 0; st && testnum < size_num; testnum++) {
2030             print_message(names[D_CBC_DES], c[D_CBC_DES][testnum],
2031                           lengths[testnum], seconds.sym);
2032             Time_F(START);
2033             count = run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2034             d = Time_F(STOP);
2035             print_result(D_CBC_DES, testnum, count, d);
2036         }
2037         for (i = 0; i < loopargs_len; i++)
2038             EVP_CIPHER_CTX_free(loopargs[i].ctx);
2039     }
2040
2041     if (doit[D_EDE3_DES]) {
2042         int st = 1;
2043
2044         for (i = 0; st && i < loopargs_len; i++) {
2045             loopargs[i].ctx = init_evp_cipher_ctx("des-ede3-cbc", deskey,
2046                                                   sizeof(deskey));
2047             st = loopargs[i].ctx != NULL;
2048         }
2049         algindex = D_EDE3_DES;
2050         for (testnum = 0; st && testnum < size_num; testnum++) {
2051             print_message(names[D_EDE3_DES], c[D_EDE3_DES][testnum],
2052                           lengths[testnum], seconds.sym);
2053             Time_F(START);
2054             count =
2055                 run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2056             d = Time_F(STOP);
2057             print_result(D_EDE3_DES, testnum, count, d);
2058         }
2059         for (i = 0; i < loopargs_len; i++)
2060             EVP_CIPHER_CTX_free(loopargs[i].ctx);
2061     }
2062
2063     for (k = 0; k < 3; k++) {
2064         algindex = D_CBC_128_AES + k;
2065         if (doit[algindex]) {
2066             int st = 1;
2067
2068             keylen = 16 + k * 8;
2069             for (i = 0; st && i < loopargs_len; i++) {
2070                 loopargs[i].ctx = init_evp_cipher_ctx(names[algindex],
2071                                                       key32, keylen);
2072                 st = loopargs[i].ctx != NULL;
2073             }
2074
2075             for (testnum = 0; st && testnum < size_num; testnum++) {
2076                 print_message(names[algindex], c[algindex][testnum],
2077                               lengths[testnum], seconds.sym);
2078                 Time_F(START);
2079                 count =
2080                     run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2081                 d = Time_F(STOP);
2082                 print_result(algindex, testnum, count, d);
2083             }
2084             for (i = 0; i < loopargs_len; i++)
2085                 EVP_CIPHER_CTX_free(loopargs[i].ctx);
2086         }
2087     }
2088
2089     for (k = 0; k < 3; k++) {
2090         algindex = D_CBC_128_CML + k;
2091         if (doit[algindex]) {
2092             int st = 1;
2093
2094             keylen = 16 + k * 8;
2095             for (i = 0; st && i < loopargs_len; i++) {
2096                 loopargs[i].ctx = init_evp_cipher_ctx(names[algindex],
2097                                                       key32, keylen);
2098                 st = loopargs[i].ctx != NULL;
2099             }
2100
2101             for (testnum = 0; st && testnum < size_num; testnum++) {
2102                 print_message(names[algindex], c[algindex][testnum],
2103                               lengths[testnum], seconds.sym);
2104                 Time_F(START);
2105                 count =
2106                     run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2107                 d = Time_F(STOP);
2108                 print_result(algindex, testnum, count, d);
2109             }
2110             for (i = 0; i < loopargs_len; i++)
2111                 EVP_CIPHER_CTX_free(loopargs[i].ctx);
2112         }
2113     }
2114
2115     for (algindex = D_RC4; algindex <= D_CBC_CAST; algindex++) {
2116         if (doit[algindex]) {
2117             int st = 1;
2118
2119             keylen = 16;
2120             for (i = 0; st && i < loopargs_len; i++) {
2121                 loopargs[i].ctx = init_evp_cipher_ctx(names[algindex],
2122                                                       key32, keylen);
2123                 st = loopargs[i].ctx != NULL;
2124             }
2125
2126             for (testnum = 0; st && testnum < size_num; testnum++) {
2127                 print_message(names[algindex], c[algindex][testnum],
2128                               lengths[testnum], seconds.sym);
2129                 Time_F(START);
2130                 count =
2131                     run_benchmark(async_jobs, EVP_Cipher_loop, loopargs);
2132                 d = Time_F(STOP);
2133                 print_result(algindex, testnum, count, d);
2134             }
2135             for (i = 0; i < loopargs_len; i++)
2136                 EVP_CIPHER_CTX_free(loopargs[i].ctx);
2137         }
2138     }
2139     if (doit[D_GHASH]) {
2140         static const char gmac_iv[] = "0123456789ab";
2141         OSSL_PARAM params[3];
2142
2143         mac = EVP_MAC_fetch(app_get0_libctx(), "GMAC", app_get0_propq());
2144         if (mac == NULL)
2145             goto end;
2146
2147         params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_CIPHER,
2148                                                      "aes-128-gcm", 0);
2149         params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_IV,
2150                                                       (char *)gmac_iv,
2151                                                       sizeof(gmac_iv) - 1);
2152         params[2] = OSSL_PARAM_construct_end();
2153
2154         for (i = 0; i < loopargs_len; i++) {
2155             loopargs[i].mctx = EVP_MAC_CTX_new(mac);
2156             if (loopargs[i].mctx == NULL)
2157                 goto end;
2158
2159             if (!EVP_MAC_init(loopargs[i].mctx, key32, 16, params))
2160                 goto end;
2161         }
2162         for (testnum = 0; testnum < size_num; testnum++) {
2163             print_message(names[D_GHASH], c[D_GHASH][testnum], lengths[testnum],
2164                           seconds.sym);
2165             Time_F(START);
2166             count = run_benchmark(async_jobs, GHASH_loop, loopargs);
2167             d = Time_F(STOP);
2168             print_result(D_GHASH, testnum, count, d);
2169             if (count < 0)
2170                 break;
2171         }
2172         for (i = 0; i < loopargs_len; i++)
2173             EVP_MAC_CTX_free(loopargs[i].mctx);
2174         EVP_MAC_free(mac);
2175         mac = NULL;
2176     }
2177
2178     if (doit[D_RAND]) {
2179         for (testnum = 0; testnum < size_num; testnum++) {
2180             print_message(names[D_RAND], c[D_RAND][testnum], lengths[testnum],
2181                           seconds.sym);
2182             Time_F(START);
2183             count = run_benchmark(async_jobs, RAND_bytes_loop, loopargs);
2184             d = Time_F(STOP);
2185             print_result(D_RAND, testnum, count, d);
2186         }
2187     }
2188
2189     if (doit[D_EVP]) {
2190         if (evp_cipher != NULL) {
2191             int (*loopfunc) (void *) = EVP_Update_loop;
2192
2193             if (multiblock && (EVP_CIPHER_get_flags(evp_cipher) &
2194                                EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)) {
2195                 multiblock_speed(evp_cipher, lengths_single, &seconds);
2196                 ret = 0;
2197                 goto end;
2198             }
2199
2200             names[D_EVP] = EVP_CIPHER_get0_name(evp_cipher);
2201
2202             if (EVP_CIPHER_get_mode(evp_cipher) == EVP_CIPH_CCM_MODE) {
2203                 loopfunc = EVP_Update_loop_ccm;
2204             } else if (aead && (EVP_CIPHER_get_flags(evp_cipher) &
2205                                 EVP_CIPH_FLAG_AEAD_CIPHER)) {
2206                 loopfunc = EVP_Update_loop_aead;
2207                 if (lengths == lengths_list) {
2208                     lengths = aead_lengths_list;
2209                     size_num = OSSL_NELEM(aead_lengths_list);
2210                 }
2211             }
2212
2213             for (testnum = 0; testnum < size_num; testnum++) {
2214                 print_message(names[D_EVP], c[D_EVP][testnum], lengths[testnum],
2215                               seconds.sym);
2216
2217                 for (k = 0; k < loopargs_len; k++) {
2218                     loopargs[k].ctx = EVP_CIPHER_CTX_new();
2219                     if (loopargs[k].ctx == NULL) {
2220                         BIO_printf(bio_err, "\nEVP_CIPHER_CTX_new failure\n");
2221                         exit(1);
2222                     }
2223                     if (!EVP_CipherInit_ex(loopargs[k].ctx, evp_cipher, NULL,
2224                                            NULL, iv, decrypt ? 0 : 1)) {
2225                         BIO_printf(bio_err, "\nEVP_CipherInit_ex failure\n");
2226                         ERR_print_errors(bio_err);
2227                         exit(1);
2228                     }
2229
2230                     EVP_CIPHER_CTX_set_padding(loopargs[k].ctx, 0);
2231
2232                     keylen = EVP_CIPHER_CTX_get_key_length(loopargs[k].ctx);
2233                     loopargs[k].key = app_malloc(keylen, "evp_cipher key");
2234                     EVP_CIPHER_CTX_rand_key(loopargs[k].ctx, loopargs[k].key);
2235                     if (!EVP_CipherInit_ex(loopargs[k].ctx, NULL, NULL,
2236                                            loopargs[k].key, NULL, -1)) {
2237                         BIO_printf(bio_err, "\nEVP_CipherInit_ex failure\n");
2238                         ERR_print_errors(bio_err);
2239                         exit(1);
2240                     }
2241                     OPENSSL_clear_free(loopargs[k].key, keylen);
2242
2243                     /* SIV mode only allows for a single Update operation */
2244                     if (EVP_CIPHER_get_mode(evp_cipher) == EVP_CIPH_SIV_MODE)
2245                         (void)EVP_CIPHER_CTX_ctrl(loopargs[k].ctx,
2246                                                   EVP_CTRL_SET_SPEED, 1, NULL);
2247                 }
2248
2249                 Time_F(START);
2250                 count = run_benchmark(async_jobs, loopfunc, loopargs);
2251                 d = Time_F(STOP);
2252                 for (k = 0; k < loopargs_len; k++)
2253                     EVP_CIPHER_CTX_free(loopargs[k].ctx);
2254                 print_result(D_EVP, testnum, count, d);
2255             }
2256         } else if (evp_md_name != NULL) {
2257             names[D_EVP] = evp_md_name;
2258
2259             for (testnum = 0; testnum < size_num; testnum++) {
2260                 print_message(names[D_EVP], c[D_EVP][testnum], lengths[testnum],
2261                               seconds.sym);
2262                 Time_F(START);
2263                 count = run_benchmark(async_jobs, EVP_Digest_md_loop, loopargs);
2264                 d = Time_F(STOP);
2265                 print_result(D_EVP, testnum, count, d);
2266                 if (count < 0)
2267                     break;
2268             }
2269         }
2270     }
2271
2272     if (doit[D_EVP_CMAC]) {
2273         OSSL_PARAM params[3];
2274         EVP_CIPHER *cipher = NULL;
2275
2276         mac = EVP_MAC_fetch(app_get0_libctx(), "CMAC", app_get0_propq());
2277         if (mac == NULL || evp_mac_ciphername == NULL)
2278             goto end;
2279         if (!opt_cipher(evp_mac_ciphername, &cipher))
2280             goto end;
2281
2282         keylen = EVP_CIPHER_get_key_length(cipher);
2283         EVP_CIPHER_free(cipher);
2284         if (keylen <= 0 || keylen > (int)sizeof(key32)) {
2285             BIO_printf(bio_err, "\nRequested CMAC cipher with unsupported key length.\n");
2286             goto end;
2287         }
2288         evp_cmac_name = app_malloc(sizeof("cmac()")
2289                                    + strlen(evp_mac_ciphername), "CMAC name");
2290         sprintf(evp_cmac_name, "cmac(%s)", evp_mac_ciphername);
2291         names[D_EVP_CMAC] = evp_cmac_name;
2292
2293         params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_CIPHER,
2294                                                      evp_mac_ciphername, 0);
2295         params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
2296                                                       (char *)key32, keylen);
2297         params[2] = OSSL_PARAM_construct_end();
2298
2299         for (i = 0; i < loopargs_len; i++) {
2300             loopargs[i].mctx = EVP_MAC_CTX_new(mac);
2301             if (loopargs[i].mctx == NULL)
2302                 goto end;
2303
2304             if (!EVP_MAC_CTX_set_params(loopargs[i].mctx, params))
2305                 goto end;
2306         }
2307
2308         for (testnum = 0; testnum < size_num; testnum++) {
2309             print_message(names[D_EVP_CMAC], c[D_EVP_CMAC][testnum],
2310                           lengths[testnum], seconds.sym);
2311             Time_F(START);
2312             count = run_benchmark(async_jobs, CMAC_loop, loopargs);
2313             d = Time_F(STOP);
2314             print_result(D_EVP_CMAC, testnum, count, d);
2315             if (count < 0)
2316                 break;
2317         }
2318         for (i = 0; i < loopargs_len; i++)
2319             EVP_MAC_CTX_free(loopargs[i].mctx);
2320         EVP_MAC_free(mac);
2321         mac = NULL;
2322     }
2323
2324     for (i = 0; i < loopargs_len; i++)
2325         if (RAND_bytes(loopargs[i].buf, 36) <= 0)
2326             goto end;
2327
2328     for (testnum = 0; testnum < RSA_NUM; testnum++) {
2329         EVP_PKEY *rsa_key = NULL;
2330         int st = 0;
2331
2332         if (!rsa_doit[testnum])
2333             continue;
2334
2335         if (primes > RSA_DEFAULT_PRIME_NUM) {
2336             /* we haven't set keys yet,  generate multi-prime RSA keys */
2337             bn = BN_new();
2338             st = bn != NULL
2339                 && BN_set_word(bn, RSA_F4)
2340                 && init_gen_str(&genctx, "RSA", NULL, 0, NULL, NULL)
2341                 && EVP_PKEY_CTX_set_rsa_keygen_bits(genctx, rsa_keys[testnum].bits) > 0
2342                 && EVP_PKEY_CTX_set1_rsa_keygen_pubexp(genctx, bn) > 0
2343                 && EVP_PKEY_CTX_set_rsa_keygen_primes(genctx, primes) > 0
2344                 && EVP_PKEY_keygen(genctx, &rsa_key);
2345             BN_free(bn);
2346             bn = NULL;
2347             EVP_PKEY_CTX_free(genctx);
2348             genctx = NULL;
2349         } else {
2350             const unsigned char *p = rsa_keys[testnum].data;
2351
2352             st = (rsa_key = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &p,
2353                                            rsa_keys[testnum].length)) != NULL;
2354         }
2355
2356         for (i = 0; st && i < loopargs_len; i++) {
2357             loopargs[i].rsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key, NULL);
2358             loopargs[i].sigsize = loopargs[i].buflen;
2359             if (loopargs[i].rsa_sign_ctx[testnum] == NULL
2360                 || EVP_PKEY_sign_init(loopargs[i].rsa_sign_ctx[testnum]) <= 0
2361                 || EVP_PKEY_sign(loopargs[i].rsa_sign_ctx[testnum],
2362                                  loopargs[i].buf2,
2363                                  &loopargs[i].sigsize,
2364                                  loopargs[i].buf, 36) <= 0)
2365                 st = 0;
2366         }
2367         if (!st) {
2368             BIO_printf(bio_err,
2369                        "RSA sign setup failure.  No RSA sign will be done.\n");
2370             ERR_print_errors(bio_err);
2371             op_count = 1;
2372         } else {
2373             pkey_print_message("private", "rsa",
2374                                rsa_c[testnum][0], rsa_keys[testnum].bits,
2375                                seconds.rsa);
2376             /* RSA_blinding_on(rsa_key[testnum],NULL); */
2377             Time_F(START);
2378             count = run_benchmark(async_jobs, RSA_sign_loop, loopargs);
2379             d = Time_F(STOP);
2380             BIO_printf(bio_err,
2381                        mr ? "+R1:%ld:%d:%.2f\n"
2382                        : "%ld %u bits private RSA's in %.2fs\n",
2383                        count, rsa_keys[testnum].bits, d);
2384             rsa_results[testnum][0] = (double)count / d;
2385             op_count = count;
2386         }
2387
2388         for (i = 0; st && i < loopargs_len; i++) {
2389             loopargs[i].rsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key,
2390                                                                    NULL);
2391             if (loopargs[i].rsa_verify_ctx[testnum] == NULL
2392                 || EVP_PKEY_verify_init(loopargs[i].rsa_verify_ctx[testnum]) <= 0
2393                 || EVP_PKEY_verify(loopargs[i].rsa_verify_ctx[testnum],
2394                                    loopargs[i].buf2,
2395                                    loopargs[i].sigsize,
2396                                    loopargs[i].buf, 36) <= 0)
2397                 st = 0;
2398         }
2399         if (!st) {
2400             BIO_printf(bio_err,
2401                        "RSA verify setup failure.  No RSA verify will be done.\n");
2402             ERR_print_errors(bio_err);
2403             rsa_doit[testnum] = 0;
2404         } else {
2405             pkey_print_message("public", "rsa",
2406                                rsa_c[testnum][1], rsa_keys[testnum].bits,
2407                                seconds.rsa);
2408             Time_F(START);
2409             count = run_benchmark(async_jobs, RSA_verify_loop, loopargs);
2410             d = Time_F(STOP);
2411             BIO_printf(bio_err,
2412                        mr ? "+R2:%ld:%d:%.2f\n"
2413                        : "%ld %u bits public RSA's in %.2fs\n",
2414                        count, rsa_keys[testnum].bits, d);
2415             rsa_results[testnum][1] = (double)count / d;
2416         }
2417
2418         if (op_count <= 1) {
2419             /* if longer than 10s, don't do any more */
2420             stop_it(rsa_doit, testnum);
2421         }
2422         EVP_PKEY_free(rsa_key);
2423     }
2424
2425     for (testnum = 0; testnum < DSA_NUM; testnum++) {
2426         EVP_PKEY *dsa_key = NULL;
2427         int st;
2428
2429         if (!dsa_doit[testnum])
2430             continue;
2431
2432         st = (dsa_key = get_dsa(dsa_bits[testnum])) != NULL;
2433
2434         for (i = 0; st && i < loopargs_len; i++) {
2435             loopargs[i].dsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(dsa_key,
2436                                                                  NULL);
2437             loopargs[i].sigsize = loopargs[i].buflen;
2438             if (loopargs[i].dsa_sign_ctx[testnum] == NULL
2439                 || EVP_PKEY_sign_init(loopargs[i].dsa_sign_ctx[testnum]) <= 0
2440
2441                 || EVP_PKEY_sign(loopargs[i].dsa_sign_ctx[testnum],
2442                                  loopargs[i].buf2,
2443                                  &loopargs[i].sigsize,
2444                                  loopargs[i].buf, 20) <= 0)
2445                 st = 0;
2446         }
2447         if (!st) {
2448             BIO_printf(bio_err,
2449                        "DSA sign setup failure.  No DSA sign will be done.\n");
2450             ERR_print_errors(bio_err);
2451             op_count = 1;
2452         } else {
2453             pkey_print_message("sign", "dsa",
2454                                dsa_c[testnum][0], dsa_bits[testnum],
2455                                seconds.dsa);
2456             Time_F(START);
2457             count = run_benchmark(async_jobs, DSA_sign_loop, loopargs);
2458             d = Time_F(STOP);
2459             BIO_printf(bio_err,
2460                        mr ? "+R3:%ld:%u:%.2f\n"
2461                        : "%ld %u bits DSA signs in %.2fs\n",
2462                        count, dsa_bits[testnum], d);
2463             dsa_results[testnum][0] = (double)count / d;
2464             op_count = count;
2465         }
2466
2467         for (i = 0; st && i < loopargs_len; i++) {
2468             loopargs[i].dsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(dsa_key,
2469                                                                    NULL);
2470             if (loopargs[i].dsa_verify_ctx[testnum] == NULL
2471                 || EVP_PKEY_verify_init(loopargs[i].dsa_verify_ctx[testnum]) <= 0
2472                 || EVP_PKEY_verify(loopargs[i].dsa_verify_ctx[testnum],
2473                                    loopargs[i].buf2,
2474                                    loopargs[i].sigsize,
2475                                    loopargs[i].buf, 36) <= 0)
2476                 st = 0;
2477         }
2478         if (!st) {
2479             BIO_printf(bio_err,
2480                        "DSA verify setup failure.  No DSA verify will be done.\n");
2481             ERR_print_errors(bio_err);
2482             dsa_doit[testnum] = 0;
2483         } else {
2484             pkey_print_message("verify", "dsa",
2485                                dsa_c[testnum][1], dsa_bits[testnum],
2486                                seconds.dsa);
2487             Time_F(START);
2488             count = run_benchmark(async_jobs, DSA_verify_loop, loopargs);
2489             d = Time_F(STOP);
2490             BIO_printf(bio_err,
2491                        mr ? "+R4:%ld:%u:%.2f\n"
2492                        : "%ld %u bits DSA verify in %.2fs\n",
2493                        count, dsa_bits[testnum], d);
2494             dsa_results[testnum][1] = (double)count / d;
2495         }
2496
2497         if (op_count <= 1) {
2498             /* if longer than 10s, don't do any more */
2499             stop_it(dsa_doit, testnum);
2500         }
2501         EVP_PKEY_free(dsa_key);
2502     }
2503
2504     for (testnum = 0; testnum < ECDSA_NUM; testnum++) {
2505         EVP_PKEY *ecdsa_key = NULL;
2506         int st;
2507
2508         if (!ecdsa_doit[testnum])
2509             continue;
2510
2511         st = (ecdsa_key = get_ecdsa(&ec_curves[testnum])) != NULL;
2512
2513         for (i = 0; st && i < loopargs_len; i++) {
2514             loopargs[i].ecdsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(ecdsa_key,
2515                                                                    NULL);
2516             loopargs[i].sigsize = loopargs[i].buflen;
2517             if (loopargs[i].ecdsa_sign_ctx[testnum] == NULL
2518                 || EVP_PKEY_sign_init(loopargs[i].ecdsa_sign_ctx[testnum]) <= 0
2519
2520                 || EVP_PKEY_sign(loopargs[i].ecdsa_sign_ctx[testnum],
2521                                  loopargs[i].buf2,
2522                                  &loopargs[i].sigsize,
2523                                  loopargs[i].buf, 20) <= 0)
2524                 st = 0;
2525         }
2526         if (!st) {
2527             BIO_printf(bio_err,
2528                        "ECDSA sign setup failure.  No ECDSA sign will be done.\n");
2529             ERR_print_errors(bio_err);
2530             op_count = 1;
2531         } else {
2532             pkey_print_message("sign", "ecdsa",
2533                                ecdsa_c[testnum][0], ec_curves[testnum].bits,
2534                                seconds.ecdsa);
2535             Time_F(START);
2536             count = run_benchmark(async_jobs, ECDSA_sign_loop, loopargs);
2537             d = Time_F(STOP);
2538             BIO_printf(bio_err,
2539                        mr ? "+R5:%ld:%u:%.2f\n"
2540                        : "%ld %u bits ECDSA signs in %.2fs\n",
2541                        count, ec_curves[testnum].bits, d);
2542             ecdsa_results[testnum][0] = (double)count / d;
2543             op_count = count;
2544         }
2545
2546         for (i = 0; st && i < loopargs_len; i++) {
2547             loopargs[i].ecdsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(ecdsa_key,
2548                                                                      NULL);
2549             if (loopargs[i].ecdsa_verify_ctx[testnum] == NULL
2550                 || EVP_PKEY_verify_init(loopargs[i].ecdsa_verify_ctx[testnum]) <= 0
2551                 || EVP_PKEY_verify(loopargs[i].ecdsa_verify_ctx[testnum],
2552                                    loopargs[i].buf2,
2553                                    loopargs[i].sigsize,
2554                                    loopargs[i].buf, 20) <= 0)
2555                 st = 0;
2556         }
2557         if (!st) {
2558             BIO_printf(bio_err,
2559                        "ECDSA verify setup failure.  No ECDSA verify will be done.\n");
2560             ERR_print_errors(bio_err);
2561             ecdsa_doit[testnum] = 0;
2562         } else {
2563             pkey_print_message("verify", "ecdsa",
2564                                ecdsa_c[testnum][1], ec_curves[testnum].bits,
2565                                seconds.ecdsa);
2566             Time_F(START);
2567             count = run_benchmark(async_jobs, ECDSA_verify_loop, loopargs);
2568             d = Time_F(STOP);
2569             BIO_printf(bio_err,
2570                        mr ? "+R6:%ld:%u:%.2f\n"
2571                        : "%ld %u bits ECDSA verify in %.2fs\n",
2572                        count, ec_curves[testnum].bits, d);
2573             ecdsa_results[testnum][1] = (double)count / d;
2574         }
2575
2576         if (op_count <= 1) {
2577             /* if longer than 10s, don't do any more */
2578             stop_it(ecdsa_doit, testnum);
2579         }
2580     }
2581
2582     for (testnum = 0; testnum < EC_NUM; testnum++) {
2583         int ecdh_checks = 1;
2584
2585         if (!ecdh_doit[testnum])
2586             continue;
2587
2588         for (i = 0; i < loopargs_len; i++) {
2589             EVP_PKEY_CTX *test_ctx = NULL;
2590             EVP_PKEY_CTX *ctx = NULL;
2591             EVP_PKEY *key_A = NULL;
2592             EVP_PKEY *key_B = NULL;
2593             size_t outlen;
2594             size_t test_outlen;
2595
2596             if ((key_A = get_ecdsa(&ec_curves[testnum])) == NULL /* generate secret key A */
2597                 || (key_B = get_ecdsa(&ec_curves[testnum])) == NULL /* generate secret key B */
2598                 || (ctx = EVP_PKEY_CTX_new(key_A, NULL)) == NULL /* derivation ctx from skeyA */
2599                 || EVP_PKEY_derive_init(ctx) <= 0 /* init derivation ctx */
2600                 || EVP_PKEY_derive_set_peer(ctx, key_B) <= 0 /* set peer pubkey in ctx */
2601                 || EVP_PKEY_derive(ctx, NULL, &outlen) <= 0 /* determine max length */
2602                 || outlen == 0 /* ensure outlen is a valid size */
2603                 || outlen > MAX_ECDH_SIZE /* avoid buffer overflow */) {
2604                 ecdh_checks = 0;
2605                 BIO_printf(bio_err, "ECDH key generation failure.\n");
2606                 ERR_print_errors(bio_err);
2607                 op_count = 1;
2608                 break;
2609             }
2610
2611             /*
2612              * Here we perform a test run, comparing the output of a*B and b*A;
2613              * we try this here and assume that further EVP_PKEY_derive calls
2614              * never fail, so we can skip checks in the actually benchmarked
2615              * code, for maximum performance.
2616              */
2617             if ((test_ctx = EVP_PKEY_CTX_new(key_B, NULL)) == NULL /* test ctx from skeyB */
2618                 || !EVP_PKEY_derive_init(test_ctx) /* init derivation test_ctx */
2619                 || !EVP_PKEY_derive_set_peer(test_ctx, key_A) /* set peer pubkey in test_ctx */
2620                 || !EVP_PKEY_derive(test_ctx, NULL, &test_outlen) /* determine max length */
2621                 || !EVP_PKEY_derive(ctx, loopargs[i].secret_a, &outlen) /* compute a*B */
2622                 || !EVP_PKEY_derive(test_ctx, loopargs[i].secret_b, &test_outlen) /* compute b*A */
2623                 || test_outlen != outlen /* compare output length */) {
2624                 ecdh_checks = 0;
2625                 BIO_printf(bio_err, "ECDH computation failure.\n");
2626                 ERR_print_errors(bio_err);
2627                 op_count = 1;
2628                 break;
2629             }
2630
2631             /* Compare the computation results: CRYPTO_memcmp() returns 0 if equal */
2632             if (CRYPTO_memcmp(loopargs[i].secret_a,
2633                               loopargs[i].secret_b, outlen)) {
2634                 ecdh_checks = 0;
2635                 BIO_printf(bio_err, "ECDH computations don't match.\n");
2636                 ERR_print_errors(bio_err);
2637                 op_count = 1;
2638                 break;
2639             }
2640
2641             loopargs[i].ecdh_ctx[testnum] = ctx;
2642             loopargs[i].outlen[testnum] = outlen;
2643
2644             EVP_PKEY_free(key_A);
2645             EVP_PKEY_free(key_B);
2646             EVP_PKEY_CTX_free(test_ctx);
2647             test_ctx = NULL;
2648         }
2649         if (ecdh_checks != 0) {
2650             pkey_print_message("", "ecdh",
2651                                ecdh_c[testnum][0],
2652                                ec_curves[testnum].bits, seconds.ecdh);
2653             Time_F(START);
2654             count =
2655                 run_benchmark(async_jobs, ECDH_EVP_derive_key_loop, loopargs);
2656             d = Time_F(STOP);
2657             BIO_printf(bio_err,
2658                        mr ? "+R7:%ld:%d:%.2f\n" :
2659                        "%ld %u-bits ECDH ops in %.2fs\n", count,
2660                        ec_curves[testnum].bits, d);
2661             ecdh_results[testnum][0] = (double)count / d;
2662             op_count = count;
2663         }
2664
2665         if (op_count <= 1) {
2666             /* if longer than 10s, don't do any more */
2667             stop_it(ecdh_doit, testnum);
2668         }
2669     }
2670
2671     for (testnum = 0; testnum < EdDSA_NUM; testnum++) {
2672         int st = 1;
2673         EVP_PKEY *ed_pkey = NULL;
2674         EVP_PKEY_CTX *ed_pctx = NULL;
2675
2676         if (!eddsa_doit[testnum])
2677             continue;           /* Ignore Curve */
2678         for (i = 0; i < loopargs_len; i++) {
2679             loopargs[i].eddsa_ctx[testnum] = EVP_MD_CTX_new();
2680             if (loopargs[i].eddsa_ctx[testnum] == NULL) {
2681                 st = 0;
2682                 break;
2683             }
2684             loopargs[i].eddsa_ctx2[testnum] = EVP_MD_CTX_new();
2685             if (loopargs[i].eddsa_ctx2[testnum] == NULL) {
2686                 st = 0;
2687                 break;
2688             }
2689
2690             if ((ed_pctx = EVP_PKEY_CTX_new_id(ed_curves[testnum].nid,
2691                                                NULL)) == NULL
2692                 || EVP_PKEY_keygen_init(ed_pctx) <= 0
2693                 || EVP_PKEY_keygen(ed_pctx, &ed_pkey) <= 0) {
2694                 st = 0;
2695                 EVP_PKEY_CTX_free(ed_pctx);
2696                 break;
2697             }
2698             EVP_PKEY_CTX_free(ed_pctx);
2699
2700             if (!EVP_DigestSignInit(loopargs[i].eddsa_ctx[testnum], NULL, NULL,
2701                                     NULL, ed_pkey)) {
2702                 st = 0;
2703                 EVP_PKEY_free(ed_pkey);
2704                 break;
2705             }
2706             if (!EVP_DigestVerifyInit(loopargs[i].eddsa_ctx2[testnum], NULL,
2707                                       NULL, NULL, ed_pkey)) {
2708                 st = 0;
2709                 EVP_PKEY_free(ed_pkey);
2710                 break;
2711             }
2712
2713             EVP_PKEY_free(ed_pkey);
2714             ed_pkey = NULL;
2715         }
2716         if (st == 0) {
2717             BIO_printf(bio_err, "EdDSA failure.\n");
2718             ERR_print_errors(bio_err);
2719             op_count = 1;
2720         } else {
2721             for (i = 0; i < loopargs_len; i++) {
2722                 /* Perform EdDSA signature test */
2723                 loopargs[i].sigsize = ed_curves[testnum].sigsize;
2724                 st = EVP_DigestSign(loopargs[i].eddsa_ctx[testnum],
2725                                     loopargs[i].buf2, &loopargs[i].sigsize,
2726                                     loopargs[i].buf, 20);
2727                 if (st == 0)
2728                     break;
2729             }
2730             if (st == 0) {
2731                 BIO_printf(bio_err,
2732                            "EdDSA sign failure.  No EdDSA sign will be done.\n");
2733                 ERR_print_errors(bio_err);
2734                 op_count = 1;
2735             } else {
2736                 pkey_print_message("sign", ed_curves[testnum].name,
2737                                    eddsa_c[testnum][0],
2738                                    ed_curves[testnum].bits, seconds.eddsa);
2739                 Time_F(START);
2740                 count = run_benchmark(async_jobs, EdDSA_sign_loop, loopargs);
2741                 d = Time_F(STOP);
2742
2743                 BIO_printf(bio_err,
2744                            mr ? "+R8:%ld:%u:%s:%.2f\n" :
2745                            "%ld %u bits %s signs in %.2fs \n",
2746                            count, ed_curves[testnum].bits,
2747                            ed_curves[testnum].name, d);
2748                 eddsa_results[testnum][0] = (double)count / d;
2749                 op_count = count;
2750             }
2751             /* Perform EdDSA verification test */
2752             for (i = 0; i < loopargs_len; i++) {
2753                 st = EVP_DigestVerify(loopargs[i].eddsa_ctx2[testnum],
2754                                       loopargs[i].buf2, loopargs[i].sigsize,
2755                                       loopargs[i].buf, 20);
2756                 if (st != 1)
2757                     break;
2758             }
2759             if (st != 1) {
2760                 BIO_printf(bio_err,
2761                            "EdDSA verify failure.  No EdDSA verify will be done.\n");
2762                 ERR_print_errors(bio_err);
2763                 eddsa_doit[testnum] = 0;
2764             } else {
2765                 pkey_print_message("verify", ed_curves[testnum].name,
2766                                    eddsa_c[testnum][1],
2767                                    ed_curves[testnum].bits, seconds.eddsa);
2768                 Time_F(START);
2769                 count = run_benchmark(async_jobs, EdDSA_verify_loop, loopargs);
2770                 d = Time_F(STOP);
2771                 BIO_printf(bio_err,
2772                            mr ? "+R9:%ld:%u:%s:%.2f\n"
2773                            : "%ld %u bits %s verify in %.2fs\n",
2774                            count, ed_curves[testnum].bits,
2775                            ed_curves[testnum].name, d);
2776                 eddsa_results[testnum][1] = (double)count / d;
2777             }
2778
2779             if (op_count <= 1) {
2780                 /* if longer than 10s, don't do any more */
2781                 stop_it(eddsa_doit, testnum);
2782             }
2783         }
2784     }
2785
2786 #ifndef OPENSSL_NO_SM2
2787     for (testnum = 0; testnum < SM2_NUM; testnum++) {
2788         int st = 1;
2789         EVP_PKEY *sm2_pkey = NULL;
2790
2791         if (!sm2_doit[testnum])
2792             continue;           /* Ignore Curve */
2793         /* Init signing and verification */
2794         for (i = 0; i < loopargs_len; i++) {
2795             EVP_PKEY_CTX *sm2_pctx = NULL;
2796             EVP_PKEY_CTX *sm2_vfy_pctx = NULL;
2797             EVP_PKEY_CTX *pctx = NULL;
2798             st = 0;
2799
2800             loopargs[i].sm2_ctx[testnum] = EVP_MD_CTX_new();
2801             loopargs[i].sm2_vfy_ctx[testnum] = EVP_MD_CTX_new();
2802             if (loopargs[i].sm2_ctx[testnum] == NULL
2803                     || loopargs[i].sm2_vfy_ctx[testnum] == NULL)
2804                 break;
2805
2806             sm2_pkey = NULL;
2807
2808             st = !((pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_SM2, NULL)) == NULL
2809                 || EVP_PKEY_keygen_init(pctx) <= 0
2810                 || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx,
2811                     sm2_curves[testnum].nid) <= 0
2812                 || EVP_PKEY_keygen(pctx, &sm2_pkey) <= 0);
2813             EVP_PKEY_CTX_free(pctx);
2814             if (st == 0)
2815                 break;
2816
2817             st = 0; /* set back to zero */
2818             /* attach it sooner to rely on main final cleanup */
2819             loopargs[i].sm2_pkey[testnum] = sm2_pkey;
2820             loopargs[i].sigsize = EVP_PKEY_get_size(sm2_pkey);
2821
2822             sm2_pctx = EVP_PKEY_CTX_new(sm2_pkey, NULL);
2823             sm2_vfy_pctx = EVP_PKEY_CTX_new(sm2_pkey, NULL);
2824             if (sm2_pctx == NULL || sm2_vfy_pctx == NULL) {
2825                 EVP_PKEY_CTX_free(sm2_vfy_pctx);
2826                 break;
2827             }
2828
2829             /* attach them directly to respective ctx */
2830             EVP_MD_CTX_set_pkey_ctx(loopargs[i].sm2_ctx[testnum], sm2_pctx);
2831             EVP_MD_CTX_set_pkey_ctx(loopargs[i].sm2_vfy_ctx[testnum], sm2_vfy_pctx);
2832
2833             /*
2834              * No need to allow user to set an explicit ID here, just use
2835              * the one defined in the 'draft-yang-tls-tl13-sm-suites' I-D.
2836              */
2837             if (EVP_PKEY_CTX_set1_id(sm2_pctx, SM2_ID, SM2_ID_LEN) != 1
2838                 || EVP_PKEY_CTX_set1_id(sm2_vfy_pctx, SM2_ID, SM2_ID_LEN) != 1)
2839                 break;
2840
2841             if (!EVP_DigestSignInit(loopargs[i].sm2_ctx[testnum], NULL,
2842                                     EVP_sm3(), NULL, sm2_pkey))
2843                 break;
2844             if (!EVP_DigestVerifyInit(loopargs[i].sm2_vfy_ctx[testnum], NULL,
2845                                       EVP_sm3(), NULL, sm2_pkey))
2846                 break;
2847             st = 1;         /* mark loop as succeeded */
2848         }
2849         if (st == 0) {
2850             BIO_printf(bio_err, "SM2 init failure.\n");
2851             ERR_print_errors(bio_err);
2852             op_count = 1;
2853         } else {
2854             for (i = 0; i < loopargs_len; i++) {
2855                 /* Perform SM2 signature test */
2856                 st = EVP_DigestSign(loopargs[i].sm2_ctx[testnum],
2857                                     loopargs[i].buf2, &loopargs[i].sigsize,
2858                                     loopargs[i].buf, 20);
2859                 if (st == 0)
2860                     break;
2861             }
2862             if (st == 0) {
2863                 BIO_printf(bio_err,
2864                            "SM2 sign failure.  No SM2 sign will be done.\n");
2865                 ERR_print_errors(bio_err);
2866                 op_count = 1;
2867             } else {
2868                 pkey_print_message("sign", sm2_curves[testnum].name,
2869                                    sm2_c[testnum][0],
2870                                    sm2_curves[testnum].bits, seconds.sm2);
2871                 Time_F(START);
2872                 count = run_benchmark(async_jobs, SM2_sign_loop, loopargs);
2873                 d = Time_F(STOP);
2874
2875                 BIO_printf(bio_err,
2876                            mr ? "+R10:%ld:%u:%s:%.2f\n" :
2877                            "%ld %u bits %s signs in %.2fs \n",
2878                            count, sm2_curves[testnum].bits,
2879                            sm2_curves[testnum].name, d);
2880                 sm2_results[testnum][0] = (double)count / d;
2881                 op_count = count;
2882             }
2883
2884             /* Perform SM2 verification test */
2885             for (i = 0; i < loopargs_len; i++) {
2886                 st = EVP_DigestVerify(loopargs[i].sm2_vfy_ctx[testnum],
2887                                       loopargs[i].buf2, loopargs[i].sigsize,
2888                                       loopargs[i].buf, 20);
2889                 if (st != 1)
2890                     break;
2891             }
2892             if (st != 1) {
2893                 BIO_printf(bio_err,
2894                            "SM2 verify failure.  No SM2 verify will be done.\n");
2895                 ERR_print_errors(bio_err);
2896                 sm2_doit[testnum] = 0;
2897             } else {
2898                 pkey_print_message("verify", sm2_curves[testnum].name,
2899                                    sm2_c[testnum][1],
2900                                    sm2_curves[testnum].bits, seconds.sm2);
2901                 Time_F(START);
2902                 count = run_benchmark(async_jobs, SM2_verify_loop, loopargs);
2903                 d = Time_F(STOP);
2904                 BIO_printf(bio_err,
2905                            mr ? "+R11:%ld:%u:%s:%.2f\n"
2906                            : "%ld %u bits %s verify in %.2fs\n",
2907                            count, sm2_curves[testnum].bits,
2908                            sm2_curves[testnum].name, d);
2909                 sm2_results[testnum][1] = (double)count / d;
2910             }
2911
2912             if (op_count <= 1) {
2913                 /* if longer than 10s, don't do any more */
2914                 for (testnum++; testnum < SM2_NUM; testnum++)
2915                     sm2_doit[testnum] = 0;
2916             }
2917         }
2918     }
2919 #endif                         /* OPENSSL_NO_SM2 */
2920
2921 #ifndef OPENSSL_NO_DH
2922     for (testnum = 0; testnum < FFDH_NUM; testnum++) {
2923         int ffdh_checks = 1;
2924
2925         if (!ffdh_doit[testnum])
2926             continue;
2927
2928         for (i = 0; i < loopargs_len; i++) {
2929             EVP_PKEY *pkey_A = NULL;
2930             EVP_PKEY *pkey_B = NULL;
2931             EVP_PKEY_CTX *ffdh_ctx = NULL;
2932             EVP_PKEY_CTX *test_ctx = NULL;
2933             size_t secret_size;
2934             size_t test_out;
2935
2936             /* Ensure that the error queue is empty */
2937             if (ERR_peek_error()) {
2938                 BIO_printf(bio_err,
2939                            "WARNING: the error queue contains previous unhandled errors.\n");
2940                 ERR_print_errors(bio_err);
2941             }
2942
2943             pkey_A = EVP_PKEY_new();
2944             if (!pkey_A) {
2945                 BIO_printf(bio_err, "Error while initialising EVP_PKEY (out of memory?).\n");
2946                 ERR_print_errors(bio_err);
2947                 op_count = 1;
2948                 ffdh_checks = 0;
2949                 break;
2950             }
2951             pkey_B = EVP_PKEY_new();
2952             if (!pkey_B) {
2953                 BIO_printf(bio_err, "Error while initialising EVP_PKEY (out of memory?).\n");
2954                 ERR_print_errors(bio_err);
2955                 op_count = 1;
2956                 ffdh_checks = 0;
2957                 break;
2958             }
2959
2960             ffdh_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_DH, NULL);
2961             if (!ffdh_ctx) {
2962                 BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n");
2963                 ERR_print_errors(bio_err);
2964                 op_count = 1;
2965                 ffdh_checks = 0;
2966                 break;
2967             }
2968
2969             if (EVP_PKEY_keygen_init(ffdh_ctx) <= 0) {
2970                 BIO_printf(bio_err, "Error while initialising EVP_PKEY_CTX.\n");
2971                 ERR_print_errors(bio_err);
2972                 op_count = 1;
2973                 ffdh_checks = 0;
2974                 break;
2975             }
2976             if (EVP_PKEY_CTX_set_dh_nid(ffdh_ctx, ffdh_params[testnum].nid) <= 0) {
2977                 BIO_printf(bio_err, "Error setting DH key size for keygen.\n");
2978                 ERR_print_errors(bio_err);
2979                 op_count = 1;
2980                 ffdh_checks = 0;
2981                 break;
2982             }
2983
2984             if (EVP_PKEY_keygen(ffdh_ctx, &pkey_A) <= 0 ||
2985                 EVP_PKEY_keygen(ffdh_ctx, &pkey_B) <= 0) {
2986                 BIO_printf(bio_err, "FFDH key generation failure.\n");
2987                 ERR_print_errors(bio_err);
2988                 op_count = 1;
2989                 ffdh_checks = 0;
2990                 break;
2991             }
2992
2993             EVP_PKEY_CTX_free(ffdh_ctx);
2994
2995             /*
2996              * check if the derivation works correctly both ways so that
2997              * we know if future derive calls will fail, and we can skip
2998              * error checking in benchmarked code
2999              */
3000             ffdh_ctx = EVP_PKEY_CTX_new(pkey_A, NULL);
3001             if (ffdh_ctx == NULL) {
3002                 BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n");
3003                 ERR_print_errors(bio_err);
3004                 op_count = 1;
3005                 ffdh_checks = 0;
3006                 break;
3007             }
3008             if (EVP_PKEY_derive_init(ffdh_ctx) <= 0) {
3009                 BIO_printf(bio_err, "FFDH derivation context init failure.\n");
3010                 ERR_print_errors(bio_err);
3011                 op_count = 1;
3012                 ffdh_checks = 0;
3013                 break;
3014             }
3015             if (EVP_PKEY_derive_set_peer(ffdh_ctx, pkey_B) <= 0) {
3016                 BIO_printf(bio_err, "Assigning peer key for derivation failed.\n");
3017                 ERR_print_errors(bio_err);
3018                 op_count = 1;
3019                 ffdh_checks = 0;
3020                 break;
3021             }
3022             if (EVP_PKEY_derive(ffdh_ctx, NULL, &secret_size) <= 0) {
3023                 BIO_printf(bio_err, "Checking size of shared secret failed.\n");
3024                 ERR_print_errors(bio_err);
3025                 op_count = 1;
3026                 ffdh_checks = 0;
3027                 break;
3028             }
3029             if (secret_size > MAX_FFDH_SIZE) {
3030                 BIO_printf(bio_err, "Assertion failure: shared secret too large.\n");
3031                 op_count = 1;
3032                 ffdh_checks = 0;
3033                 break;
3034             }
3035             if (EVP_PKEY_derive(ffdh_ctx,
3036                                 loopargs[i].secret_ff_a,
3037                                 &secret_size) <= 0) {
3038                 BIO_printf(bio_err, "Shared secret derive failure.\n");
3039                 ERR_print_errors(bio_err);
3040                 op_count = 1;
3041                 ffdh_checks = 0;
3042                 break;
3043             }
3044             /* Now check from side B */
3045             test_ctx = EVP_PKEY_CTX_new(pkey_B, NULL);
3046             if (!test_ctx) {
3047                 BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n");
3048                 ERR_print_errors(bio_err);
3049                 op_count = 1;
3050                 ffdh_checks = 0;
3051                 break;
3052             }
3053             if (!EVP_PKEY_derive_init(test_ctx) ||
3054                 !EVP_PKEY_derive_set_peer(test_ctx, pkey_A) ||
3055                 !EVP_PKEY_derive(test_ctx, NULL, &test_out) ||
3056                 !EVP_PKEY_derive(test_ctx, loopargs[i].secret_ff_b, &test_out) ||
3057                 test_out != secret_size) {
3058                 BIO_printf(bio_err, "FFDH computation failure.\n");
3059                 op_count = 1;
3060                 ffdh_checks = 0;
3061                 break;
3062             }
3063
3064             /* compare the computed secrets */
3065             if (CRYPTO_memcmp(loopargs[i].secret_ff_a,
3066                               loopargs[i].secret_ff_b, secret_size)) {
3067                 BIO_printf(bio_err, "FFDH computations don't match.\n");
3068                 ERR_print_errors(bio_err);
3069                 op_count = 1;
3070                 ffdh_checks = 0;
3071                 break;
3072             }
3073
3074             loopargs[i].ffdh_ctx[testnum] = ffdh_ctx;
3075
3076             EVP_PKEY_free(pkey_A);
3077             pkey_A = NULL;
3078             EVP_PKEY_free(pkey_B);
3079             pkey_B = NULL;
3080             EVP_PKEY_CTX_free(test_ctx);
3081             test_ctx = NULL;
3082         }
3083         if (ffdh_checks != 0) {
3084             pkey_print_message("", "ffdh", ffdh_c[testnum][0],
3085                                ffdh_params[testnum].bits, seconds.ffdh);
3086             Time_F(START);
3087             count =
3088                 run_benchmark(async_jobs, FFDH_derive_key_loop, loopargs);
3089             d = Time_F(STOP);
3090             BIO_printf(bio_err,
3091                        mr ? "+R12:%ld:%d:%.2f\n" :
3092                        "%ld %u-bits FFDH ops in %.2fs\n", count,
3093                        ffdh_params[testnum].bits, d);
3094             ffdh_results[testnum][0] = (double)count / d;
3095             op_count = count;
3096         }
3097         if (op_count <= 1) {
3098             /* if longer than 10s, don't do any more */
3099             stop_it(ffdh_doit, testnum);
3100         }
3101     }
3102 #endif  /* OPENSSL_NO_DH */
3103 #ifndef NO_FORK
3104  show_res:
3105 #endif
3106     if (!mr) {
3107         printf("version: %s\n", OpenSSL_version(OPENSSL_FULL_VERSION_STRING));
3108         printf("%s\n", OpenSSL_version(OPENSSL_BUILT_ON));
3109         printf("options: %s\n", BN_options());
3110         printf("%s\n", OpenSSL_version(OPENSSL_CFLAGS));
3111         printf("%s\n", OpenSSL_version(OPENSSL_CPU_INFO));
3112     }
3113
3114     if (pr_header) {
3115         if (mr) {
3116             printf("+H");
3117         } else {
3118             printf("The 'numbers' are in 1000s of bytes per second processed.\n");
3119             printf("type        ");
3120         }
3121         for (testnum = 0; testnum < size_num; testnum++)
3122             printf(mr ? ":%d" : "%7d bytes", lengths[testnum]);
3123         printf("\n");
3124     }
3125
3126     for (k = 0; k < ALGOR_NUM; k++) {
3127         if (!doit[k])
3128             continue;
3129         if (mr)
3130             printf("+F:%u:%s", k, names[k]);
3131         else
3132             printf("%-13s", names[k]);
3133         for (testnum = 0; testnum < size_num; testnum++) {
3134             if (results[k][testnum] > 10000 && !mr)
3135                 printf(" %11.2fk", results[k][testnum] / 1e3);
3136             else
3137                 printf(mr ? ":%.2f" : " %11.2f ", results[k][testnum]);
3138         }
3139         printf("\n");
3140     }
3141     testnum = 1;
3142     for (k = 0; k < RSA_NUM; k++) {
3143         if (!rsa_doit[k])
3144             continue;
3145         if (testnum && !mr) {
3146             printf("%18ssign    verify    sign/s verify/s\n", " ");
3147             testnum = 0;
3148         }
3149         if (mr)
3150             printf("+F2:%u:%u:%f:%f\n",
3151                    k, rsa_keys[k].bits, rsa_results[k][0], rsa_results[k][1]);
3152         else
3153             printf("rsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n",
3154                    rsa_keys[k].bits, 1.0 / rsa_results[k][0], 1.0 / rsa_results[k][1],
3155                    rsa_results[k][0], rsa_results[k][1]);
3156     }
3157     testnum = 1;
3158     for (k = 0; k < DSA_NUM; k++) {
3159         if (!dsa_doit[k])
3160             continue;
3161         if (testnum && !mr) {
3162             printf("%18ssign    verify    sign/s verify/s\n", " ");
3163             testnum = 0;
3164         }
3165         if (mr)
3166             printf("+F3:%u:%u:%f:%f\n",
3167                    k, dsa_bits[k], dsa_results[k][0], dsa_results[k][1]);
3168         else
3169             printf("dsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n",
3170                    dsa_bits[k], 1.0 / dsa_results[k][0], 1.0 / dsa_results[k][1],
3171                    dsa_results[k][0], dsa_results[k][1]);
3172     }
3173     testnum = 1;
3174     for (k = 0; k < OSSL_NELEM(ecdsa_doit); k++) {
3175         if (!ecdsa_doit[k])
3176             continue;
3177         if (testnum && !mr) {
3178             printf("%30ssign    verify    sign/s verify/s\n", " ");
3179             testnum = 0;
3180         }
3181
3182         if (mr)
3183             printf("+F4:%u:%u:%f:%f\n",
3184                    k, ec_curves[k].bits,
3185                    ecdsa_results[k][0], ecdsa_results[k][1]);
3186         else
3187             printf("%4u bits ecdsa (%s) %8.4fs %8.4fs %8.1f %8.1f\n",
3188                    ec_curves[k].bits, ec_curves[k].name,
3189                    1.0 / ecdsa_results[k][0], 1.0 / ecdsa_results[k][1],
3190                    ecdsa_results[k][0], ecdsa_results[k][1]);
3191     }
3192
3193     testnum = 1;
3194     for (k = 0; k < EC_NUM; k++) {
3195         if (!ecdh_doit[k])
3196             continue;
3197         if (testnum && !mr) {
3198             printf("%30sop      op/s\n", " ");
3199             testnum = 0;
3200         }
3201         if (mr)
3202             printf("+F5:%u:%u:%f:%f\n",
3203                    k, ec_curves[k].bits,
3204                    ecdh_results[k][0], 1.0 / ecdh_results[k][0]);
3205
3206         else
3207             printf("%4u bits ecdh (%s) %8.4fs %8.1f\n",
3208                    ec_curves[k].bits, ec_curves[k].name,
3209                    1.0 / ecdh_results[k][0], ecdh_results[k][0]);
3210     }
3211
3212     testnum = 1;
3213     for (k = 0; k < OSSL_NELEM(eddsa_doit); k++) {
3214         if (!eddsa_doit[k])
3215             continue;
3216         if (testnum && !mr) {
3217             printf("%30ssign    verify    sign/s verify/s\n", " ");
3218             testnum = 0;
3219         }
3220
3221         if (mr)
3222             printf("+F6:%u:%u:%s:%f:%f\n",
3223                    k, ed_curves[k].bits, ed_curves[k].name,
3224                    eddsa_results[k][0], eddsa_results[k][1]);
3225         else
3226             printf("%4u bits EdDSA (%s) %8.4fs %8.4fs %8.1f %8.1f\n",
3227                    ed_curves[k].bits, ed_curves[k].name,
3228                    1.0 / eddsa_results[k][0], 1.0 / eddsa_results[k][1],
3229                    eddsa_results[k][0], eddsa_results[k][1]);
3230     }
3231
3232 #ifndef OPENSSL_NO_SM2
3233     testnum = 1;
3234     for (k = 0; k < OSSL_NELEM(sm2_doit); k++) {
3235         if (!sm2_doit[k])
3236             continue;
3237         if (testnum && !mr) {
3238             printf("%30ssign    verify    sign/s verify/s\n", " ");
3239             testnum = 0;
3240         }
3241
3242         if (mr)
3243             printf("+F7:%u:%u:%s:%f:%f\n",
3244                    k, sm2_curves[k].bits, sm2_curves[k].name,
3245                    sm2_results[k][0], sm2_results[k][1]);
3246         else
3247             printf("%4u bits SM2 (%s) %8.4fs %8.4fs %8.1f %8.1f\n",
3248                    sm2_curves[k].bits, sm2_curves[k].name,
3249                    1.0 / sm2_results[k][0], 1.0 / sm2_results[k][1],
3250                    sm2_results[k][0], sm2_results[k][1]);
3251     }
3252 #endif
3253 #ifndef OPENSSL_NO_DH
3254     testnum = 1;
3255     for (k = 0; k < FFDH_NUM; k++) {
3256         if (!ffdh_doit[k])
3257             continue;
3258         if (testnum && !mr) {
3259             printf("%23sop     op/s\n", " ");
3260             testnum = 0;
3261         }
3262         if (mr)
3263             printf("+F8:%u:%u:%f:%f\n",
3264                    k, ffdh_params[k].bits,
3265                    ffdh_results[k][0], 1.0 / ffdh_results[k][0]);
3266
3267         else
3268             printf("%4u bits ffdh %8.4fs %8.1f\n",
3269                    ffdh_params[k].bits,
3270                    1.0 / ffdh_results[k][0], ffdh_results[k][0]);
3271     }
3272 #endif /* OPENSSL_NO_DH */
3273
3274     ret = 0;
3275
3276  end:
3277     ERR_print_errors(bio_err);
3278     for (i = 0; i < loopargs_len; i++) {
3279         OPENSSL_free(loopargs[i].buf_malloc);
3280         OPENSSL_free(loopargs[i].buf2_malloc);
3281
3282         BN_free(bn);
3283         EVP_PKEY_CTX_free(genctx);
3284         for (k = 0; k < RSA_NUM; k++) {
3285             EVP_PKEY_CTX_free(loopargs[i].rsa_sign_ctx[k]);
3286             EVP_PKEY_CTX_free(loopargs[i].rsa_verify_ctx[k]);
3287         }
3288 #ifndef OPENSSL_NO_DH
3289         OPENSSL_free(loopargs[i].secret_ff_a);
3290         OPENSSL_free(loopargs[i].secret_ff_b);
3291         for (k = 0; k < FFDH_NUM; k++)
3292             EVP_PKEY_CTX_free(loopargs[i].ffdh_ctx[k]);
3293 #endif
3294         for (k = 0; k < DSA_NUM; k++) {
3295             EVP_PKEY_CTX_free(loopargs[i].dsa_sign_ctx[k]);
3296             EVP_PKEY_CTX_free(loopargs[i].dsa_verify_ctx[k]);
3297         }
3298         for (k = 0; k < ECDSA_NUM; k++) {
3299             EVP_PKEY_CTX_free(loopargs[i].ecdsa_sign_ctx[k]);
3300             EVP_PKEY_CTX_free(loopargs[i].ecdsa_verify_ctx[k]);
3301         }
3302         for (k = 0; k < EC_NUM; k++)
3303             EVP_PKEY_CTX_free(loopargs[i].ecdh_ctx[k]);
3304         for (k = 0; k < EdDSA_NUM; k++) {
3305             EVP_MD_CTX_free(loopargs[i].eddsa_ctx[k]);
3306             EVP_MD_CTX_free(loopargs[i].eddsa_ctx2[k]);
3307         }
3308 #ifndef OPENSSL_NO_SM2
3309         for (k = 0; k < SM2_NUM; k++) {
3310             EVP_PKEY_CTX *pctx = NULL;
3311
3312             /* free signing ctx */
3313             if (loopargs[i].sm2_ctx[k] != NULL
3314                 && (pctx = EVP_MD_CTX_get_pkey_ctx(loopargs[i].sm2_ctx[k])) != NULL)
3315                 EVP_PKEY_CTX_free(pctx);
3316             EVP_MD_CTX_free(loopargs[i].sm2_ctx[k]);
3317             /* free verification ctx */
3318             if (loopargs[i].sm2_vfy_ctx[k] != NULL
3319                 && (pctx = EVP_MD_CTX_get_pkey_ctx(loopargs[i].sm2_vfy_ctx[k])) != NULL)
3320                 EVP_PKEY_CTX_free(pctx);
3321             EVP_MD_CTX_free(loopargs[i].sm2_vfy_ctx[k]);
3322             /* free pkey */
3323             EVP_PKEY_free(loopargs[i].sm2_pkey[k]);
3324         }
3325 #endif
3326         OPENSSL_free(loopargs[i].secret_a);
3327         OPENSSL_free(loopargs[i].secret_b);
3328     }
3329     OPENSSL_free(evp_hmac_name);
3330     OPENSSL_free(evp_cmac_name);
3331
3332     if (async_jobs > 0) {
3333         for (i = 0; i < loopargs_len; i++)
3334             ASYNC_WAIT_CTX_free(loopargs[i].wait_ctx);
3335     }
3336
3337     if (async_init) {
3338         ASYNC_cleanup_thread();
3339     }
3340     OPENSSL_free(loopargs);
3341     release_engine(e);
3342     EVP_CIPHER_free(evp_cipher);
3343     EVP_MAC_free(mac);
3344     return ret;
3345 }
3346
3347 static void print_message(const char *s, long num, int length, int tm)
3348 {
3349     BIO_printf(bio_err,
3350                mr ? "+DT:%s:%d:%d\n"
3351                : "Doing %s for %ds on %d size blocks: ", s, tm, length);
3352     (void)BIO_flush(bio_err);
3353     run = 1;
3354     alarm(tm);
3355 }
3356
3357 static void pkey_print_message(const char *str, const char *str2, long num,
3358                                unsigned int bits, int tm)
3359 {
3360     BIO_printf(bio_err,
3361                mr ? "+DTP:%d:%s:%s:%d\n"
3362                : "Doing %u bits %s %s's for %ds: ", bits, str, str2, tm);
3363     (void)BIO_flush(bio_err);
3364     run = 1;
3365     alarm(tm);
3366 }
3367
3368 static void print_result(int alg, int run_no, int count, double time_used)
3369 {
3370     if (count == -1) {
3371         BIO_printf(bio_err, "%s error!\n", names[alg]);
3372         ERR_print_errors(bio_err);
3373         return;
3374     }
3375     BIO_printf(bio_err,
3376                mr ? "+R:%d:%s:%f\n"
3377                : "%d %s's in %.2fs\n", count, names[alg], time_used);
3378     results[alg][run_no] = ((double)count) / time_used * lengths[run_no];
3379 }
3380
3381 #ifndef NO_FORK
3382 static char *sstrsep(char **string, const char *delim)
3383 {
3384     char isdelim[256];
3385     char *token = *string;
3386
3387     if (**string == 0)
3388         return NULL;
3389
3390     memset(isdelim, 0, sizeof(isdelim));
3391     isdelim[0] = 1;
3392
3393     while (*delim) {
3394         isdelim[(unsigned char)(*delim)] = 1;
3395         delim++;
3396     }
3397
3398     while (!isdelim[(unsigned char)(**string)])
3399         (*string)++;
3400
3401     if (**string) {
3402         **string = 0;
3403         (*string)++;
3404     }
3405
3406     return token;
3407 }
3408
3409 static int do_multi(int multi, int size_num)
3410 {
3411     int n;
3412     int fd[2];
3413     int *fds;
3414     static char sep[] = ":";
3415
3416     fds = app_malloc(sizeof(*fds) * multi, "fd buffer for do_multi");
3417     for (n = 0; n < multi; ++n) {
3418         if (pipe(fd) == -1) {
3419             BIO_printf(bio_err, "pipe failure\n");
3420             exit(1);
3421         }
3422         fflush(stdout);
3423         (void)BIO_flush(bio_err);
3424         if (fork()) {
3425             close(fd[1]);
3426             fds[n] = fd[0];
3427         } else {
3428             close(fd[0]);
3429             close(1);
3430             if (dup(fd[1]) == -1) {
3431                 BIO_printf(bio_err, "dup failed\n");
3432                 exit(1);
3433             }
3434             close(fd[1]);
3435             mr = 1;
3436             usertime = 0;
3437             OPENSSL_free(fds);
3438             return 0;
3439         }
3440         printf("Forked child %d\n", n);
3441     }
3442
3443     /* for now, assume the pipe is long enough to take all the output */
3444     for (n = 0; n < multi; ++n) {
3445         FILE *f;
3446         char buf[1024];
3447         char *p;
3448
3449         f = fdopen(fds[n], "r");
3450         while (fgets(buf, sizeof(buf), f)) {
3451             p = strchr(buf, '\n');
3452             if (p)
3453                 *p = '\0';
3454             if (buf[0] != '+') {
3455                 BIO_printf(bio_err,
3456                            "Don't understand line '%s' from child %d\n", buf,
3457                            n);
3458                 continue;
3459             }
3460             printf("Got: %s from %d\n", buf, n);
3461             p = buf;
3462             if (CHECK_AND_SKIP_PREFIX(p, "+F:")) {
3463                 int alg;
3464                 int j;
3465
3466                 alg = atoi(sstrsep(&p, sep));
3467                 sstrsep(&p, sep);
3468                 for (j = 0; j < size_num; ++j)
3469                     results[alg][j] += atof(sstrsep(&p, sep));
3470             } else if (CHECK_AND_SKIP_PREFIX(p, "+F2:")) {
3471                 int k;
3472                 double d;
3473
3474                 k = atoi(sstrsep(&p, sep));
3475                 sstrsep(&p, sep);
3476
3477                 d = atof(sstrsep(&p, sep));
3478                 rsa_results[k][0] += d;
3479
3480                 d = atof(sstrsep(&p, sep));
3481                 rsa_results[k][1] += d;
3482             } else if (CHECK_AND_SKIP_PREFIX(p, "+F3:")) {
3483                 int k;
3484                 double d;
3485
3486                 k = atoi(sstrsep(&p, sep));
3487                 sstrsep(&p, sep);
3488
3489                 d = atof(sstrsep(&p, sep));
3490                 dsa_results[k][0] += d;
3491
3492                 d = atof(sstrsep(&p, sep));
3493                 dsa_results[k][1] += d;
3494             } else if (CHECK_AND_SKIP_PREFIX(p, "+F4:")) {
3495                 int k;
3496                 double d;
3497
3498                 k = atoi(sstrsep(&p, sep));
3499                 sstrsep(&p, sep);
3500
3501                 d = atof(sstrsep(&p, sep));
3502                 ecdsa_results[k][0] += d;
3503
3504                 d = atof(sstrsep(&p, sep));
3505                 ecdsa_results[k][1] += d;
3506             } else if (CHECK_AND_SKIP_PREFIX(p, "+F5:")) {
3507                 int k;
3508                 double d;
3509
3510                 k = atoi(sstrsep(&p, sep));
3511                 sstrsep(&p, sep);
3512
3513                 d = atof(sstrsep(&p, sep));
3514                 ecdh_results[k][0] += d;
3515             } else if (CHECK_AND_SKIP_PREFIX(p, "+F6:")) {
3516                 int k;
3517                 double d;
3518
3519                 k = atoi(sstrsep(&p, sep));
3520                 sstrsep(&p, sep);
3521                 sstrsep(&p, sep);
3522
3523                 d = atof(sstrsep(&p, sep));
3524                 eddsa_results[k][0] += d;
3525
3526                 d = atof(sstrsep(&p, sep));
3527                 eddsa_results[k][1] += d;
3528 # ifndef OPENSSL_NO_SM2
3529             } else if (CHECK_AND_SKIP_PREFIX(p, "+F7:")) {
3530                 int k;
3531                 double d;
3532
3533                 k = atoi(sstrsep(&p, sep));
3534                 sstrsep(&p, sep);
3535                 sstrsep(&p, sep);
3536
3537                 d = atof(sstrsep(&p, sep));
3538                 sm2_results[k][0] += d;
3539
3540                 d = atof(sstrsep(&p, sep));
3541                 sm2_results[k][1] += d;
3542 # endif /* OPENSSL_NO_SM2 */
3543 # ifndef OPENSSL_NO_DH
3544             } else if (CHECK_AND_SKIP_PREFIX(p, "+F8:")) {
3545                 int k;
3546                 double d;
3547
3548                 k = atoi(sstrsep(&p, sep));
3549                 sstrsep(&p, sep);
3550
3551                 d = atof(sstrsep(&p, sep));
3552                 ffdh_results[k][0] += d;
3553 # endif /* OPENSSL_NO_DH */
3554             } else if (HAS_PREFIX(buf, "+H:")) {
3555                 ;
3556             } else {
3557                 BIO_printf(bio_err, "Unknown type '%s' from child %d\n", buf,
3558                            n);
3559             }
3560         }
3561
3562         fclose(f);
3563     }
3564     OPENSSL_free(fds);
3565     return 1;
3566 }
3567 #endif
3568
3569 static void multiblock_speed(const EVP_CIPHER *evp_cipher, int lengths_single,
3570                              const openssl_speed_sec_t *seconds)
3571 {
3572     static const int mblengths_list[] =
3573         { 8 * 1024, 2 * 8 * 1024, 4 * 8 * 1024, 8 * 8 * 1024, 8 * 16 * 1024 };
3574     const int *mblengths = mblengths_list;
3575     int j, count, keylen, num = OSSL_NELEM(mblengths_list);
3576     const char *alg_name;
3577     unsigned char *inp = NULL, *out = NULL, *key, no_key[32], no_iv[16];
3578     EVP_CIPHER_CTX *ctx = NULL;
3579     double d = 0.0;
3580
3581     if (lengths_single) {
3582         mblengths = &lengths_single;
3583         num = 1;
3584     }
3585
3586     inp = app_malloc(mblengths[num - 1], "multiblock input buffer");
3587     out = app_malloc(mblengths[num - 1] + 1024, "multiblock output buffer");
3588     if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
3589         app_bail_out("failed to allocate cipher context\n");
3590     if (!EVP_EncryptInit_ex(ctx, evp_cipher, NULL, NULL, no_iv))
3591         app_bail_out("failed to initialise cipher context\n");
3592
3593     if ((keylen = EVP_CIPHER_CTX_get_key_length(ctx)) < 0) {
3594         BIO_printf(bio_err, "Impossible negative key length: %d\n", keylen);
3595         goto err;
3596     }
3597     key = app_malloc(keylen, "evp_cipher key");
3598     if (!EVP_CIPHER_CTX_rand_key(ctx, key))
3599         app_bail_out("failed to generate random cipher key\n");
3600     if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, NULL))
3601         app_bail_out("failed to set cipher key\n");
3602     OPENSSL_clear_free(key, keylen);
3603
3604     if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
3605                              sizeof(no_key), no_key))
3606         app_bail_out("failed to set AEAD key\n");
3607     if ((alg_name = EVP_CIPHER_get0_name(evp_cipher)) == NULL)
3608         app_bail_out("failed to get cipher name\n");
3609
3610     for (j = 0; j < num; j++) {
3611         print_message(alg_name, 0, mblengths[j], seconds->sym);
3612         Time_F(START);
3613         for (count = 0; run && count < 0x7fffffff; count++) {
3614             unsigned char aad[EVP_AEAD_TLS1_AAD_LEN];
3615             EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
3616             size_t len = mblengths[j];
3617             int packlen;
3618
3619             memset(aad, 0, 8);  /* avoid uninitialized values */
3620             aad[8] = 23;        /* SSL3_RT_APPLICATION_DATA */
3621             aad[9] = 3;         /* version */
3622             aad[10] = 2;
3623             aad[11] = 0;        /* length */
3624             aad[12] = 0;
3625             mb_param.out = NULL;
3626             mb_param.inp = aad;
3627             mb_param.len = len;
3628             mb_param.interleave = 8;
3629
3630             packlen = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
3631                                           sizeof(mb_param), &mb_param);
3632
3633             if (packlen > 0) {
3634                 mb_param.out = out;
3635                 mb_param.inp = inp;
3636                 mb_param.len = len;
3637                 (void)EVP_CIPHER_CTX_ctrl(ctx,
3638                                           EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
3639                                           sizeof(mb_param), &mb_param);
3640             } else {
3641                 int pad;
3642
3643                 RAND_bytes(out, 16);
3644                 len += 16;
3645                 aad[11] = (unsigned char)(len >> 8);
3646                 aad[12] = (unsigned char)(len);
3647                 pad = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD,
3648                                           EVP_AEAD_TLS1_AAD_LEN, aad);
3649                 EVP_Cipher(ctx, out, inp, len + pad);
3650             }
3651         }
3652         d = Time_F(STOP);
3653         BIO_printf(bio_err, mr ? "+R:%d:%s:%f\n"
3654                    : "%d %s's in %.2fs\n", count, "evp", d);
3655         results[D_EVP][j] = ((double)count) / d * mblengths[j];
3656     }
3657
3658     if (mr) {
3659         fprintf(stdout, "+H");
3660         for (j = 0; j < num; j++)
3661             fprintf(stdout, ":%d", mblengths[j]);
3662         fprintf(stdout, "\n");
3663         fprintf(stdout, "+F:%d:%s", D_EVP, alg_name);
3664         for (j = 0; j < num; j++)
3665             fprintf(stdout, ":%.2f", results[D_EVP][j]);
3666         fprintf(stdout, "\n");
3667     } else {
3668         fprintf(stdout,
3669                 "The 'numbers' are in 1000s of bytes per second processed.\n");
3670         fprintf(stdout, "type                    ");
3671         for (j = 0; j < num; j++)
3672             fprintf(stdout, "%7d bytes", mblengths[j]);
3673         fprintf(stdout, "\n");
3674         fprintf(stdout, "%-24s", alg_name);
3675
3676         for (j = 0; j < num; j++) {
3677             if (results[D_EVP][j] > 10000)
3678                 fprintf(stdout, " %11.2fk", results[D_EVP][j] / 1e3);
3679             else
3680                 fprintf(stdout, " %11.2f ", results[D_EVP][j]);
3681         }
3682         fprintf(stdout, "\n");
3683     }
3684
3685  err:
3686     OPENSSL_free(inp);
3687     OPENSSL_free(out);
3688     EVP_CIPHER_CTX_free(ctx);
3689 }