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