wolfssl-sys 4.0.0

System bindings for WolfSSL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
/* logging.c
 *
 * Copyright (C) 2006-2026 wolfSSL Inc.
 *
 * This file is part of wolfSSL.
 *
 * wolfSSL is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * wolfSSL is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
 */

#include <wolfssl/wolfcrypt/libwolfssl_sources.h>

#if defined(OPENSSL_EXTRA) && !defined(WOLFCRYPT_ONLY)
/* avoid adding WANT_READ and WANT_WRITE to error queue */
#include <wolfssl/error-ssl.h>
#endif

#ifdef WOLFSSL_FUNC_TIME
/* WARNING: This code is only to be used for debugging performance.
 *          The code is not thread-safe.
 *          Do not use WOLFSSL_FUNC_TIME in production code.
 */
static double wc_func_start[WC_FUNC_COUNT];
static double wc_func_time[WC_FUNC_COUNT] = { 0, };
static const char* wc_func_name[WC_FUNC_COUNT] = {
    "SendHelloRequest",
    "DoHelloRequest",
    "SendClientHello",
    "DoClientHello",
    "SendServerHello",
    "DoServerHello",
    "SendEncryptedExtensions",
    "DoEncryptedExtensions",
    "SendCertificateRequest",
    "DoCertificateRequest",
    "SendCertificate",
    "DoCertificate",
    "SendCertificateVerify",
    "DoCertificateVerify",
    "SendFinished",
    "DoFinished",
    "SendKeyUpdate",
    "DoKeyUpdate",
    "SendEarlyData",
    "DoEarlyData",
    "SendNewSessionTicket",
    "DoNewSessionTicket",
    "SendServerHelloDone",
    "DoServerHelloDone",
    "SendTicket",
    "DoTicket",
    "SendClientKeyExchange",
    "DoClientKeyExchange",
    "SendCertificateStatus",
    "DoCertificateStatus",
    "SendServerKeyExchange",
    "DoServerKeyExchange",
    "SendEarlyData",
    "DoEarlyData",
};

#include <sys/time.h>

/* WARNING: This function is not portable. */
static WC_INLINE double current_time(int reset)
{
    struct timeval tv;
    gettimeofday(&tv, 0);
    (void)reset;

    return (double)tv.tv_sec + (double)tv.tv_usec / 1000000;
}
#endif /* WOLFSSL_FUNC_TIME */

#ifdef HAVE_WC_INTROSPECTION

const char *wolfSSL_configure_args(void) {
#ifdef LIBWOLFSSL_CONFIGURE_ARGS
  /* the spaces on either side are to make matching simple and efficient. */
  return " " LIBWOLFSSL_CONFIGURE_ARGS " ";
#else
  return NULL;
#endif
}

PEDANTIC_EXTENSION const char *wolfSSL_global_cflags(void) {
#ifdef LIBWOLFSSL_GLOBAL_CFLAGS
  /* the spaces on either side are to make matching simple and efficient. */
  return " " LIBWOLFSSL_GLOBAL_CFLAGS " ";
#else
  return NULL;
#endif
}

#endif /* HAVE_WC_INTROSPECTION */

#ifdef HAVE_STACK_SIZE_VERBOSE

THREAD_LS_T unsigned char *StackSizeCheck_myStack = NULL;
THREAD_LS_T size_t StackSizeCheck_stackSize = 0;
THREAD_LS_T size_t StackSizeCheck_stackSizeHWM = 0;
THREAD_LS_T size_t *StackSizeCheck_stackSizeHWM_ptr = 0;
THREAD_LS_T void *StackSizeCheck_stackOffsetPointer = 0;

#endif /* HAVE_STACK_SIZE_VERBOSE */

#if defined(DEBUG_WOLFSSL) || \
    (defined(WOLFSSL_DEBUG_CERTS) && !defined(NO_WOLFSSL_DEBUG_CERTS))

/* Set these to default values initially. */
static wolfSSL_Logging_cb LogFunction = NULL;
#ifndef WOLFSSL_LOGGINGENABLED_DEFAULT
#define WOLFSSL_LOGGINGENABLED_DEFAULT 0
#endif
static int loggingEnabled = WOLFSSL_LOGGINGENABLED_DEFAULT;
#ifndef WOLFSSL_CERT_LOG_ENABLED_DEFAULT
#define WOLFSSL_CERT_LOG_ENABLED_DEFAULT 0
#endif
#ifndef NO_WOLFSSL_DEBUG_CERTS
static int loggingCertEnabled = WOLFSSL_CERT_LOG_ENABLED_DEFAULT;
#endif
THREAD_LS_T const char* log_prefix = NULL;

#if defined(WOLFSSL_APACHE_MYNEWT)
#include "log/log.h"
static struct log mynewt_log;
#define WOLFSSL_APACHE_MYNEWT_NOT_INITALIZED 0
#define WOLFSSL_APACHE_MYNEWT_INITALIZED     1
static int loggingApacheNewtRegistered = WOLFSSL_APACHE_MYNEWT_NOT_INITALIZED;
#endif /* WOLFSSL_APACHE_MYNEWT */
#endif /* DEBUG_WOLFSSL || WOLFSSL_DEBUG_CERTS */

int wolfSSL_CertDebugging_ON(void)
{
    /* Certificate debugging is also a subset of full debugging */
#if defined(WOLFSSL_DEBUG_CERTS) || defined(DEBUG_WOLFSSL)
    #if defined(NO_WOLFSSL_DEBUG_CERTS)
        return NOT_COMPILED_IN;
    #else
        loggingCertEnabled = 1;
    #endif
    #if defined(WOLFSSL_APACHE_MYNEWT)
        if (loggingApacheNewtRegistered != WOLFSSL_APACHE_MYNEWT_INITALIZED) {
            log_register("wolfcrypt", &mynewt_log, &log_console_handler,
                                      NULL, LOG_SYSLEVEL);
            loggingApacheNewtRegistered = WOLFSSL_APACHE_MYNEWT_INITALIZED;
        }
    #endif /* WOLFSSL_APACHE_MYNEWT */
    return 0;
#else
    return NOT_COMPILED_IN;
#endif
}

int wolfSSL_CertDebugging_OFF(void)
{
#if defined(WOLFSSL_DEBUG_CERTS) || defined(DEBUG_WOLFSSL)
    #if defined(NO_WOLFSSL_DEBUG_CERTS)
        return NOT_COMPILED_IN;
    #else
        loggingCertEnabled = 0;
    #endif
    return 0;
#else
    return NOT_COMPILED_IN;
#endif
}

/* allow this to be set to NULL, so logs can be redirected to default output */
int wolfSSL_SetLoggingCb(wolfSSL_Logging_cb log_function)
{
#ifdef DEBUG_WOLFSSL
    LogFunction = log_function;
    return 0;
#else
    (void)log_function;
    return NOT_COMPILED_IN;
#endif
}

/* allow this to be set to NULL, so logs can be redirected to default output */
wolfSSL_Logging_cb wolfSSL_GetLoggingCb(void)
{
#ifdef DEBUG_WOLFSSL
    return LogFunction;
#else
    return NULL;
#endif
}


int wolfSSL_Debugging_ON(void)
{
#ifdef DEBUG_WOLFSSL
    loggingEnabled = 1;
    #ifndef NO_WOLFSSL_DEBUG_CERTS
        /* Certificate debugging is enabled by default during DEBUG_WOLFSSL,
         * unless explicitly disabled with NO_WOLFSSL_DEBUG_CERTS */
        loggingCertEnabled = 1;
    #endif
    #if defined(WOLFSSL_APACHE_MYNEWT)
        if (loggingApacheNewtRegistered != WOLFSSL_APACHE_MYNEWT_INITALIZED) {
            log_register("wolfcrypt", &mynewt_log, &log_console_handler,
                                      NULL, LOG_SYSLEVEL);
            loggingApacheNewtRegistered = WOLFSSL_APACHE_MYNEWT_INITALIZED;
        }
    #endif /* WOLFSSL_APACHE_MYNEWT */
    return 0;
#else
    return NOT_COMPILED_IN;
#endif /* DEBUG_WOLFSSL */
}


void wolfSSL_Debugging_OFF(void)
{
#ifdef DEBUG_WOLFSSL
    loggingEnabled = 0;
    #ifndef NO_WOLFSSL_DEBUG_CERTS
        loggingCertEnabled = 0;
    #endif
#endif
}

void wolfSSL_SetLoggingPrefix(const char* prefix)
{
#if defined(DEBUG_WOLFSSL) || \
   (defined(WOLFSSL_DEBUG_CERTS) && !defined(NO_WOLFSSL_DEBUG_CERTS))
    log_prefix = prefix;
#else
    (void)prefix;
#endif
}

#ifdef WOLFSSL_FUNC_TIME
/* WARNING: This code is only to be used for debugging performance.
 *          The code is not thread-safe.
 *          Do not use WOLFSSL_FUNC_TIME in production code.
 */
void WOLFSSL_START(int funcNum)
{
    if (funcNum < WC_FUNC_COUNT) {
        double now = current_time(0) * 1000.0;
    #ifdef WOLFSSL_FUNC_TIME_LOG
        WOLFSSL_DEBUG_PRINTF("%17.3f: START - %s\n",
                             now, wc_func_name[funcNum]);
    #endif
        wc_func_start[funcNum] = now;
    }
}

void WOLFSSL_END(int funcNum)
{
    if (funcNum < WC_FUNC_COUNT) {
        double now = current_time(0) * 1000.0;
        wc_func_time[funcNum] += now - wc_func_start[funcNum];
    #ifdef WOLFSSL_FUNC_TIME_LOG
        WOLFSSL_DEBUG_PRINTF("%17.3f: END   - %s\n",
                             now, wc_func_name[funcNum]);
    #endif
    }
}

void WOLFSSL_TIME(int count)
{
    int i;
    double avg, total = 0;

    for (i = 0; i < WC_FUNC_COUNT; i++) {
        if (wc_func_time[i] > 0) {
            avg = wc_func_time[i] / count;
            WOLFSSL_DEBUG_PRINTF("%8.3f ms: %s\n", avg, wc_func_name[i]);
            total += avg;
        }
    }
    WOLFSSL_DEBUG_PRINTF("%8.3f ms\n", total);
}
#endif

#if defined(DEBUG_WOLFSSL) || \
    (defined(WOLFSSL_DEBUG_CERTS) && !defined(NO_WOLFSSL_DEBUG_CERTS))

#ifdef HAVE_STACK_SIZE_VERBOSE
#include <wolfssl/wolfcrypt/mem_track.h>
#endif

static void wolfssl_log(const int logLevel, const char* const file_name,
                        int line_number, const char* const logMessage)
{
    (void)file_name;
    (void)line_number;
    if (LogFunction)
        LogFunction(logLevel, logMessage);
    else {
#if defined(WOLFSSL_USER_LOG)
        WOLFSSL_USER_LOG(logMessage);
#elif defined(WOLFSSL_DEBUG_PRINTF_FN)
    #ifdef WOLFSSL_MDK_ARM
        fflush(stdout);
    #endif
    /* see settings.h for platform-specific line endings */
    #ifndef WOLFSSL_DEBUG_LINE_ENDING
        #define WOLFSSL_DEBUG_LINE_ENDING "\n"
    #endif
        if (log_prefix != NULL) {
            if (file_name != NULL) {
                WOLFSSL_DEBUG_PRINTF_FN(WOLFSSL_DEBUG_PRINTF_FIRST_ARGS
                        "[%s]: [%s L %d] %s" WOLFSSL_DEBUG_LINE_ENDING,
                        log_prefix, file_name, line_number, logMessage);
            }
            else {
                WOLFSSL_DEBUG_PRINTF_FN(WOLFSSL_DEBUG_PRINTF_FIRST_ARGS
                   "[%s]: %s" WOLFSSL_DEBUG_LINE_ENDING, log_prefix, logMessage);
            } /* file_name check */
        }
        else {
            if (file_name != NULL) {
                WOLFSSL_DEBUG_PRINTF_FN(WOLFSSL_DEBUG_PRINTF_FIRST_ARGS
                        "[%s L %d] %s" WOLFSSL_DEBUG_LINE_ENDING,
                        file_name, line_number, logMessage);
            }
            else {
                WOLFSSL_DEBUG_PRINTF_FN(WOLFSSL_DEBUG_PRINTF_FIRST_ARGS
                        "%s" WOLFSSL_DEBUG_LINE_ENDING, logMessage);
            } /* file_name check */
        } /* log_prefix check */
    #ifdef WOLFSSL_MDK_ARM
        fflush(stdout);
    #endif
#elif defined(ARDUINO)
        wolfSSL_Arduino_Serial_Print(logMessage);
#elif defined(WOLFSSL_UTASKER)
        fnDebugMsg((char*)logMessage);
        fnDebugMsg("\r\n");
#elif defined(STACK_SIZE_CHECKPOINT_MSG) && \
      defined(HAVE_STACK_SIZE_VERBOSE) && defined(HAVE_STACK_SIZE_VERBOSE_LOG)
        STACK_SIZE_CHECKPOINT_MSG(logMessage);
#else
    #error No log method defined.
#endif
    }
}

#ifndef WOLFSSL_DEBUG_ERRORS_ONLY

/* Certificate debugging available with either regular debugging
 * DEBUG_WOLFSSL or just certificate debugging: WOLFSSL_DEBUG_CERTS */
#if (defined(WOLFSSL_DEBUG_CERTS) || defined(DEBUG_WOLFSSL)) && \
    !defined(NO_WOLFSSL_DEBUG_CERTS)
    #include <stdarg.h> /* for var args */

    #ifndef WOLFSSL_MSG_CERT_BUF_SZ
        #define WOLFSSL_MSG_CERT_BUF_SZ 140
    #endif

    int WOLFSSL_MSG_CERT(const char* msg)
    {
        /* Regular debug may have been compiled out */
        (void)loggingEnabled;

        if ((msg != NULL) && (loggingCertEnabled != 0)) {
            wolfssl_log(CERT_LOG, NULL, 0, msg);
        }
        return 0;
    }

    #ifdef XVSNPRINTF
    #ifdef __clang__
    /* tell clang argument 1 is format */
    __attribute__((__format__ (__printf__, 1, 0)))
    #endif
    int WOLFSSL_MSG_CERT_EX(const char* fmt, ...)
    {
        /* Certificate logging output may have large messages */
    #ifdef WOLFSSL_SMALL_STACK
        char*  msg;
        msg = (char*)XMALLOC(WOLFSSL_MSG_CERT_BUF_SZ, NULL,
                             DYNAMIC_TYPE_TMP_BUFFER);
        if (msg == NULL) {
            return MEMORY_E;
        }
    #else
        char msg[WOLFSSL_MSG_CERT_BUF_SZ];
    #endif
        int written;
        va_list args;
        va_start(args, fmt);
        /* Assume zero-terminated msg, len less than WOLFSSL_MSG_CERT_BUF_SZ */
        written = XVSNPRINTF(msg, WOLFSSL_MSG_CERT_BUF_SZ, fmt, args);
        va_end(args);
        if ((written > 0) && (loggingCertEnabled != 0)) {
            wolfssl_log(INFO_LOG, NULL, 0, msg);
        }
    WC_FREE_VAR_EX(msg, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        return 0;
    } /* WOLFSSL_MSG_CERT_EX */
    #endif /* XVSNPRINTF */

#else /* (!WOLFSSL_DEBUG_CERTS && !DEBUG_WOLFSSL) || NO_WOLFSSL_DEBUG_CERTS */

    #ifdef WOLF_NO_VARIADIC_MACROS
        #ifdef  __WATCOMC__
            /* Do-nothing implementation in header for OW Open Watcom V2 */
        #else
            int WOLFSSL_MSG_CERT(const char* msg)
            {
                (void)msg;
                return NOT_COMPILED_IN;
            }
           int WOLFSSL_MSG_CERT_EX(const char* fmt, ...)
           {
               (void)fmt;
               return NOT_COMPILED_IN;
           }
        #endif
    #else
        /* using a macro, see logging.h */
    #endif
#endif /* (!WOLFSSL_DEBUG_CERTS && !DEBUG_WOLFSSL) || NO_WOLFSSL_DEBUG_CERTS */

#if defined(XVSNPRINTF) && !defined(NO_WOLFSSL_MSG_EX)
#if defined(WOLFSSL_BSDKM)
    #include <machine/stdarg.h> /* for var args */
#else
    #include <stdarg.h> /* for var args */
#endif /* WOLFSSL_BSDKM */

#ifndef WOLFSSL_MSG_EX_BUF_SZ
#define WOLFSSL_MSG_EX_BUF_SZ 100
#endif

#if !defined(WOLFSSL_MSG_EX) && defined(DEBUG_WOLFSSL)
#ifdef __clang__
/* tell clang argument 1 is format */
__attribute__((__format__ (__printf__, 1, 0)))
#endif
void WOLFSSL_MSG_EX(const char* fmt, ...)
{
    if (loggingEnabled) {
        char msg[WOLFSSL_MSG_EX_BUF_SZ];
        int written;
        va_list args;
        va_start(args, fmt);
        written = XVSNPRINTF(msg, sizeof(msg), fmt, args);
        va_end(args);
        if (written > 0)
            wolfssl_log(INFO_LOG, NULL, 0, msg);
    }
}
#endif

#ifdef WOLFSSL_DEBUG_CODEPOINTS
void WOLFSSL_MSG_EX2(const char *file, int line, const char* fmt, ...)
{
    if (loggingEnabled) {
        char msg[WOLFSSL_MSG_EX_BUF_SZ];
        int written;
        va_list args;
        va_start(args, fmt);
        written = XVSNPRINTF(msg, sizeof(msg), fmt, args);
        va_end(args);
        if (written > 0)
            wolfssl_log(INFO_LOG, file, line, msg);
    }
}
#endif /* WOLFSSL_DEBUG_CODEPOINTS */

#else
    /* We need a do-nothing function when variadic macros not available */
    #ifdef WOLF_NO_VARIADIC_MACROS
        /* See header for same-name, do nothing functions */
    #else
        /* See header for same-name, do nothing macros */
    #endif
#endif /* XVSNPRINTF && !NO_WOLFSSL_MSG_EX */

#ifndef WOLFSSL_MSG
void WOLFSSL_MSG(const char* msg)
{
    if (loggingEnabled)
        wolfssl_log(INFO_LOG, NULL, 0, msg);
}
#endif

#ifdef WOLFSSL_DEBUG_CODEPOINTS
void WOLFSSL_MSG2(const char *file, int line, const char* msg)
{
    if (loggingEnabled)
        wolfssl_log(INFO_LOG, file, line, msg);
}
#endif

#ifndef WOLFSSL_BUFFER
#ifndef LINE_LEN
#define LINE_LEN 16
#endif
void WOLFSSL_BUFFER(const byte* buffer, word32 length)
{
    int i, buflen = (int)length;
    char line[(LINE_LEN * 4) + 3]; /* \t00..0F | chars...chars\0 */

    if (!loggingEnabled) {
        return;
    }

    if (!buffer) {
        wolfssl_log(INFO_LOG, NULL, 0, "\tNULL");
        return;
    }

    while (buflen > 0) {
        int bufidx = 0;
        if (XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, "\t")
            >= (int)sizeof(line) - bufidx)
        {
            goto errout;
        }
        bufidx++;

        for (i = 0; i < LINE_LEN; i++) {
            if (i < buflen) {
                if (XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, "%02x ",
                              buffer[i]) >= (int)sizeof(line) - bufidx)
                {
                    goto errout;
                }
            }
            else {
                if (XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, "   ")
                    >= (int)sizeof(line) - bufidx)
                {
                    goto errout;
                }
            }
            bufidx += 3;
        }

        if (XSNPRINTF(&line[bufidx], sizeof(line)-bufidx, "| ")
            >= (int)sizeof(line) - bufidx)
        {
            goto errout;
        }
        bufidx++;

        for (i = 0; i < LINE_LEN; i++) {
            if (i < buflen) {
                if (XSNPRINTF(&line[bufidx], sizeof(line)-bufidx,
                              "%c", 31 < buffer[i] && buffer[i] < 127
                              ? buffer[i]
                              : '.')
                    >= (int)sizeof(line) - bufidx)
                {
                    goto errout;
                }
                bufidx++;
            }
        }

        wolfssl_log(INFO_LOG, NULL, 0, line);
        buffer += LINE_LEN;
        buflen -= LINE_LEN;
    }

    return;

errout:

    wolfssl_log(INFO_LOG, NULL, 0, "\t[Buffer error while rendering]");
}
#endif /* WOLFSSL_BUFFER */

#ifndef WOLFSSL_ENTER
void WOLFSSL_ENTER(const char* msg)
{
    if (loggingEnabled) {
        char buffer[WOLFSSL_MAX_ERROR_SZ];
        if (XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Entering %s", msg)
            >= (int)sizeof(buffer))
        {
            buffer[sizeof(buffer) - 1] = 0;
        }
        wolfssl_log(ENTER_LOG, NULL, 0, buffer);
    }
}
#endif /* WOLFSSL_ENTER */

#ifdef WOLFSSL_DEBUG_CODEPOINTS
void WOLFSSL_ENTER2(const char *file, int line, const char* msg)
{
    if (loggingEnabled) {
        char buffer[WOLFSSL_MAX_ERROR_SZ];
        if (XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Entering %s", msg)
            >= (int)sizeof(buffer))
        {
            buffer[sizeof(buffer) - 1] = 0;
        }
        wolfssl_log(ENTER_LOG, file, line, buffer);
    }
}
#endif /* WOLFSSL_DEBUG_CODEPOINTS */

#ifndef WOLFSSL_LEAVE
void WOLFSSL_LEAVE(const char* msg, int ret)
{
    if (loggingEnabled) {
        char buffer[WOLFSSL_MAX_ERROR_SZ];
        if (XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Leaving %s, return %d",
                      msg, ret)
            >= (int)sizeof(buffer))
        {
            buffer[sizeof(buffer) - 1] = 0;
        }
        wolfssl_log(LEAVE_LOG, NULL, 0, buffer);
    }
}
#endif /* WOLFSSL_LEAVE */

#ifdef WOLFSSL_DEBUG_CODEPOINTS
void WOLFSSL_LEAVE2(const char *file, int line, const char* msg, int ret)
{
    if (loggingEnabled) {
        char buffer[WOLFSSL_MAX_ERROR_SZ];
        if (XSNPRINTF(buffer, sizeof(buffer), "wolfSSL Leaving %s, return %d",
                      msg, ret)
            >= (int)sizeof(buffer))
        {
            buffer[sizeof(buffer) - 1] = 0;
        }
        wolfssl_log(LEAVE_LOG, file, line, buffer);
    }
}
#endif

#ifdef WOLFSSL_DEBUG_CODEPOINTS
    /* restore the wrappers */
    #define WOLFSSL_MSG(msg) WOLFSSL_MSG2(__FILE__, __LINE__, msg)
    #define WOLFSSL_ENTER(msg) WOLFSSL_ENTER2(__FILE__, __LINE__, msg)
    #define WOLFSSL_LEAVE(msg, ret) WOLFSSL_LEAVE2(__FILE__, __LINE__, msg, ret)
    #ifdef XVSNPRINTF
/*        #define WOLFSSL_MSG_EX(fmt, args...) \
                WOLFSSL_MSG_EX2(__FILE__, __LINE__, fmt, ## args)
    */
    #endif
#endif

#ifndef WOLFSSL_IS_DEBUG_ON
int WOLFSSL_IS_DEBUG_ON(void)
{
    return loggingEnabled;
}
#endif /* WOLFSSL_IS_DEBUG_ON */
#endif /* !WOLFSSL_DEBUG_ERRORS_ONLY */

#else
    /* !(DEBUG_WOLFSSL || (WOLFSSL_DEBUG_CERTS && !NO_WOLFSSL_DEBUG_CERTS)) */
    /*
     * Create some no-op functions for compilers without variadic macros,
     * other than Open Watcom V2.
     */
    #ifdef WOLF_NO_VARIADIC_MACROS
        /* no debug and cannot use variadic macros */
        #ifdef __WATCOMC__
            /* see logging.h for no-op Watcom implementation */
        #else
            int WOLFSSL_MSG_CERT(const char* msg)
            {
                (void)msg;
                return NOT_COMPILED_IN;
            }

            int WOLFSSL_MSG_CERT_EX(const char* fmt, ...)
            {
                (void)fmt;
                return NOT_COMPILED_IN;
            }
        #endif
    #else
        /* see logging.h for variadic macros */
    #endif
#endif /* DEBUG_WOLFSSL || (WOLFSSL_DEBUG_CERTS && !NO_WOLFSSL_DEBUG_CERTS) */

/* Final catch for no-op WOLFSSL_MSG_EX needing implementation */
#ifdef __WATCOMC__
    /* See no-op implementation as needed in logging.h */
#else
    #ifdef DEBUG_WOLFSSL
        /* The empty no-op function is not needed when debugging */
    #else
        #if defined(HAVE_WOLFSSL_MSG_EX) || defined(WOLF_NO_VARIADIC_MACROS)
            void WOLFSSL_MSG_EX(const char* fmt, ...)
            {
                (void)fmt;
            }
        #else
            /* See macro in header */
        #endif
    #endif
#endif



#if defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE) || defined(HAVE_MEMCACHED)

#ifdef WOLFSSL_HAVE_ERROR_QUEUE

#ifdef ERROR_QUEUE_PER_THREAD
/* Keep the error queue in thread-local-storage. The only ways this
 * API can deliver meaningful semantics in a multi-threaded setup.
 */
#ifndef ERROR_QUEUE_MAX
/* Same as OpenSSL v1.1.x limit, note that this is per thread */
#define ERROR_QUEUE_MAX 16
#endif

struct wc_error_entry {
    char   reason[WOLFSSL_MAX_ERROR_SZ];
    char   file[WOLFSSL_MAX_ERROR_SZ];
    int    line;
    int    err;
};

struct wc_error_queue {
    struct wc_error_entry entries[ERROR_QUEUE_MAX];
    size_t head_idx;
    size_t count;
};

/* The complete queue in a thread local without allocations */
static THREAD_LS_T struct wc_error_queue wc_errors;

/* Using thread-local-storage, we do not need a mutex. */
#define ERRQ_LOCK()            0
#define ERRQ_UNLOCK()          (void)0

/**
 * Given a relative index (from head of the error list), return
 * the absolute index in the `wc_errors->entries` array for
 * the entry or -1 if no such entry exists/is present.
 */
static int get_abs_idx(int relative_idx)
{
    if ((wc_errors.count == 0) || (relative_idx >= (int)wc_errors.count)) {
        return -1;
    }
    if (relative_idx < 0) {
        return (int)((wc_errors.head_idx + wc_errors.count - 1)
                      % ERROR_QUEUE_MAX);
    }
    return (int)((wc_errors.head_idx + (size_t)relative_idx) % ERROR_QUEUE_MAX);
}

/**
 * Return the error entry at the given relative index, if
 * it exists, e.g. `relative_idx` is in a valid range.
 */
static struct wc_error_entry *get_entry(int relative_idx)
{
    int abs_idx;

    abs_idx = get_abs_idx(relative_idx);
    if (abs_idx < 0) {
        return NULL;
    }
    return &wc_errors.entries[abs_idx];
}

/**
 * Return the error code in the given error `entry` and populate
 * `file`, `reason` and `line` with its values.
 * `entry` may be NULL, in which case BAD_STATE_E is returned.
 */
static int pass_entry(struct wc_error_entry *entry,
                      const char **file, const char **reason,
                      int *line)
{
    if (entry == NULL) {
        WOLFSSL_MSG("No Error found in queue");
        return BAD_STATE_E;
    }
    if (file != NULL) {
        *file = entry->file;
    }
    if (reason != NULL) {
        *reason = entry->reason;
    }
    if (line != NULL) {
        *line = entry->line;
    }
    return entry->err;
}

/**
 * Assign entry with values, resets all previously present values.
 */
static void set_entry(struct wc_error_entry *entry, int error,
                      const char *file, const char *reason, int line)
{
    size_t sz;

    XMEMSET(entry, 0, sizeof(struct wc_error_entry));
    entry->err = error;

    entry->line  = line;
    sz = XSTRLEN(reason);
    if (sz > WOLFSSL_MAX_ERROR_SZ - 1) {
        sz = WOLFSSL_MAX_ERROR_SZ - 1;
    }
    if (sz > 0) {
        XMEMCPY(entry->reason, reason, sz);
        entry->reason[WOLFSSL_MAX_ERROR_SZ - 1] = '\0';
    }

    sz = XSTRLEN(file);
    if (sz > WOLFSSL_MAX_ERROR_SZ - 1) {
        sz = WOLFSSL_MAX_ERROR_SZ - 1;
    }
    if (sz > 0) {
        XMEMCPY(entry->file, file, sz);
        entry->file[WOLFSSL_MAX_ERROR_SZ - 1]  = '\0';
    }
}

/* Internal function that is called by wolfCrypt_Init() */
int wc_LoggingInit(void)
{
    return 0;
}

/* internal function that is called by wolfCrypt_Cleanup */
int wc_LoggingCleanup(void)
{
    /* clear logging entries */
    wc_ClearErrorNodes();
    return 0;
}

/**
 * Get the values from the HEAD of the ERR queue, but keep it in place.
 * If the queue is empty, return BAD_STATE_E.
 */
int wc_PeekErrorNode(int idx, const char **file, const char **reason,
                     int *line)
{
    return pass_entry(get_entry(idx), file, reason, line);
}

/**
 * Get the values from the HEAD of the ERR queue and remove it.
 * If the queue is empty, return BAD_STATE_E.
 */
int wc_PullErrorNode(const char **file, const char **reason, int *line)
{
    struct wc_error_entry *entry;
    int ret;

    entry = get_entry(0);
    ret = pass_entry(entry, file, reason, line);

    if (entry != NULL) {
      wc_RemoveErrorNode(0);
    }
    return ret;
}

/* create new error node and add it to the queue
 * buffers are assumed to be of size WOLFSSL_MAX_ERROR_SZ for this internal
 * function. */
int wc_AddErrorNode(int error, int line, char* reason, char* file)
{
    struct wc_error_entry *entry;
    size_t idx;

    if (wc_errors.count >= ERROR_QUEUE_MAX) {
        WOLFSSL_MSG("Error queue is full, at ERROR_QUEUE_MAX");
        return MEMORY_E;
    }

    idx = (wc_errors.head_idx + wc_errors.count) % ERROR_QUEUE_MAX;
    entry = &wc_errors.entries[idx];
    set_entry(entry, error, file, reason, line);
    ++wc_errors.count;

    return 0;
}

/**
 * Remove the entry at relative position `relative_idx` from the ERR queue.
 * For `relative_idx == 0` it removes the queue's head entry, for -1
 * it removes the last entry in the queue.
 */
void wc_RemoveErrorNode(int relative_idx)
{
    int abs_idx = get_abs_idx(relative_idx);

    if (abs_idx >= 0) {
        size_t move_count;
        if (abs_idx >= (int)wc_errors.head_idx) {
            /* removed entry sits "above" head (or is head),
             * move entries below it "up" */
            move_count = (size_t)abs_idx - wc_errors.head_idx;
            if (move_count > 0) {
                XMEMMOVE(&wc_errors.entries[wc_errors.head_idx + 1],
                         &wc_errors.entries[wc_errors.head_idx],
                         sizeof(wc_errors.entries[0]) * move_count);
            }
            wc_errors.head_idx = (wc_errors.head_idx + 1) % ERROR_QUEUE_MAX;
            --wc_errors.count;
        }
        else {
            /* removed entry sits "below" head (wrap around),
             * move entries above it "down" */
            int last_idx = get_abs_idx(-1);
            if (last_idx >= abs_idx) {  /* this SHOULD always be true */
                move_count = (size_t)(last_idx - abs_idx);
                if (move_count > 0) {
                    XMEMMOVE(&wc_errors.entries[abs_idx],
                             &wc_errors.entries[abs_idx + 1],
                             sizeof(wc_errors.entries[0]) * move_count);
                }
                --wc_errors.count;
            }
        }
    }
}

/**
 * Clear the ERR queue.
 */
void wc_ClearErrorNodes(void)
{
    if (wc_errors.count > 0) {
        XMEMSET(&wc_errors, 0, sizeof(wc_errors));
    }
}

int wc_SetLoggingHeap(void* h)
{
    (void)h;
    return 0;
}

int wc_ERR_remove_state(void)
{
    wc_ClearErrorNodes();
    return 0;
}

/**
 * Get the first entry's values in the ERR queue that is not filtered
 * by the provided `ignore_err` callback. All ignored entries are removed,
 * making the returned entry the head of the ERR queue afterwards.
 *
 * In case all entries are ignored, the ERR queue will be empty afterwards.
 * For an empty ERR queue  0 is returned.
 *
 * `ignore_err` may be NULL, in which case this returns the HEAD values.
 *
 * `flags` is present for OpenSSL compatibility, but will always be
 * set to 0, since we do not keep flags at ERR entries.
 */
unsigned long wc_PeekErrorNodeLineData(const char **file, int *line,
                                       const char **data, int *flags,
                                       int (*ignore_err)(int err))
{
    WOLFSSL_ENTER("wc_PeekErrorNodeLineData");

    /* No data or flags stored - error display only in Nginx. */
    if (data != NULL) {
        *data = "";
    }
    if (flags != NULL) {
        *flags = 0;
    }

    while (1) {
        int ret = wc_PeekErrorNode(0, file, NULL, line);
        if (ret == WC_NO_ERR_TRACE(BAD_STATE_E)) {
            WOLFSSL_MSG("Issue peeking at error node in queue");
            return 0;
        }
        /* OpenSSL uses positive error codes */
        if (ret < 0) {
            ret = -ret;
        }
        /* an error that the caller wants to ignore? */
        if (ignore_err && ignore_err(ret)) {
          wc_RemoveErrorNode(0);
          continue;
        }

        return (unsigned long)ret;
    }
}

/**
 * Get the error value at the HEAD of the ERR queue or 0 if the queue
 * is empty. The HEAD entry is removed by this call.
 */
int wc_GetErrorNodeErr(void)
{
    int ret;

    WOLFSSL_ENTER("wc_GetErrorNodeErr");

    ret = wc_PullErrorNode(NULL, NULL, NULL);
    if (ret < 0) {
        if (ret == WC_NO_ERR_TRACE(BAD_STATE_E)) {
            ret = 0; /* no errors in queue */
        }
        else {
            WOLFSSL_MSG("Error with pulling error node!");
            WOLFSSL_LEAVE("wolfSSL_ERR_get_error", ret);
            ret = 0 - ret; /* return absolute value of error */
            /* panic and try to clear out nodes */
            wc_ClearErrorNodes();
        }
    }
    return ret;
}

#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM)
/* This callback allows the application to provide a custom error printing
 * function. */
void wc_ERR_print_errors_cb(int (*cb)(const char *str, size_t len, void *u),
                            void *u)
{
    size_t i;

    WOLFSSL_ENTER("wc_ERR_print_errors_cb");

    if (cb == NULL) {
        /* Invalid param */
        return;
    }

    for (i = 0; i < wc_errors.count; ++i) {
        struct wc_error_entry *entry = get_entry((int)i);
        if (entry == NULL)
            break;
        cb(entry->reason, XSTRLEN(entry->reason), u);
    }

    wc_ClearErrorNodes();
}
#endif /* !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) */

#else /* ERROR_QUEUE_PER_THREAD */
/* Error queue is a global list. This is the original implementation and
 * the fallback on platforms that do not have thread-local-storage.
 *
 * Access and manipulations of the list are protected by a mutex, however
 * that does not prevent errors from another thread showing up. Therefore,
 * its usefulness  is limited to applications with restricted thread
 * concurrency in using wolfSSL.
 */
#ifndef ERROR_QUEUE_MAX
/* With a global list, we allow a higher limit. */
#define ERROR_QUEUE_MAX 100
#endif

/* The information we keep about a single error */
struct wc_error_queue {
    void*  heap; /* the heap hint used with nodes creation */
    struct wc_error_queue* next;
    struct wc_error_queue* prev;
    char   error[WOLFSSL_MAX_ERROR_SZ];
    char   file[WOLFSSL_MAX_ERROR_SZ];
    int    value;
    int    line;
};

/* The global list of errors encountered */
static struct wc_error_queue* wc_errors;
static int wc_errors_count = 0;
/* pointer to last node in queue to make insertion O(1) */
static struct wc_error_queue* wc_last_node;
/* The 'current' cursor the application is using to access the list */
static struct wc_error_queue* wc_current_node;

/* heap info currently used for allocation of entries */
static void* wc_error_heap;

/* mutex for list operation protection */
static wolfSSL_Mutex wc_error_mutex WOLFSSL_MUTEX_INITIALIZER_CLAUSE(wc_error_mutex);
#define ERRQ_MUTEX_INIT()      wc_InitMutex(&wc_error_mutex)
#define ERRQ_MUTEX_FREE()      wc_FreeMutex(&wc_error_mutex)
#define ERRQ_LOCK()            wc_LockMutex(&wc_error_mutex)
#define ERRQ_UNLOCK()          wc_UnLockMutex(&wc_error_mutex)

/* Internal function that is called by wolfCrypt_Init() */
int wc_LoggingInit(void)
{
#ifndef WOLFSSL_MUTEX_INITIALIZER
    if (ERRQ_MUTEX_INIT() != 0) {
        WOLFSSL_MSG("Bad Init Mutex");
        return BAD_MUTEX_E;
    }
#endif
    wc_errors_count = 0;
    wc_errors          = NULL;
    wc_current_node    = NULL;
    wc_last_node       = NULL;
    return 0;
}


/* internal function that is called by wolfCrypt_Cleanup */
int wc_LoggingCleanup(void)
{
    /* clear logging entries */
    wc_ClearErrorNodes();
    /* free mutex */
#ifndef WOLFSSL_MUTEX_INITIALIZER
    if (ERRQ_MUTEX_FREE() != 0) {
        WOLFSSL_MSG("Bad Mutex free");
        return BAD_MUTEX_E;
    }
#endif
    return 0;
}

static int peekErrorNode(int idx, const char **file, const char **reason,
        int *line)
{
    struct wc_error_queue* err;

    if (idx < 0) {
        err = wc_last_node;
    }
    else {
        int i;

        err = (struct wc_error_queue*)wc_errors;
        for (i = 0; i < idx; i++) {
            if (err == NULL) {
                WOLFSSL_MSG("Error node not found. Bad index?");
                return BAD_FUNC_ARG;
            }
            err = err->next;
        }
    }

    if (err == NULL) {
        WOLFSSL_MSG("No Errors in queue");
        return BAD_STATE_E;
    }

    if (file != NULL) {
        *file = err->file;
    }
    if (reason != NULL) {
        *reason = err->error;
    }
    if (line != NULL) {
        *line = err->line;
    }

    return err->value;
}

/* peek at an error node
 *
 * idx : if -1 then the most recent node is looked at,
 *       otherwise search through queue for node at the given index starting
 *          from the absolute head wc_errors
 * file  : pointer to internal file string
 * reason : pointer to internal error reason
 * line  : line number that error happened at
 *
 * Returns a negative value in error case, on success returns the nodes error
 * value which is positive (absolute value)
 */
int wc_PeekErrorNode(int idx, const char **file, const char **reason,
        int *line)
{
    int ret;

    if (ERRQ_LOCK() != 0) {
        WOLFSSL_MSG("Lock debug mutex failed");
        return BAD_MUTEX_E;
    }
    ret = peekErrorNode(idx, file, reason, line);
    ERRQ_UNLOCK();
    return ret;
}

static int pullErrorNode(const char **file, const char **reason, int *line)
{
    struct wc_error_queue* err;
    int value;

    err = wc_current_node;
    if (err == NULL) {
        WOLFSSL_MSG("No Errors in queue");
        return BAD_STATE_E;
    }

    if (file != NULL) {
        *file = err->file;
    }
    if (reason != NULL) {
        *reason = err->error;
    }
    if (line != NULL) {
        *line = err->line;
    }
    value = err->value;
    wc_current_node = err->next;

    return value;
}

/* Pulls the current node from error queue and increments current state.
 * Note: this does not delete nodes because input arguments are pointing to
 *       node buffers.
 *
 * file   pointer to file that error was in. Can be NULL to return no file.
 * reason error string giving reason for error. Can be NULL to return no reason.
 * line   return line number of where error happened.
 *
 * returns the error value on success and BAD_MUTEX_E or BAD_STATE_E on failure
 */
int wc_PullErrorNode(const char **file, const char **reason, int *line)
{
    int value;

    if (ERRQ_LOCK() != 0) {
        WOLFSSL_MSG("Lock debug mutex failed");
        return BAD_MUTEX_E;
    }

    value = pullErrorNode(file, reason, line);

    ERRQ_UNLOCK();
    return value;
}

/* create new error node and add it to the queue
 * buffers are assumed to be of size WOLFSSL_MAX_ERROR_SZ for this internal
 * function. */
int wc_AddErrorNode(int error, int line, char* buf, char* file)
{
    struct wc_error_queue* err;

    if (wc_errors_count >= ERROR_QUEUE_MAX) {
        WOLFSSL_MSG("Error queue is full, at ERROR_QUEUE_MAX");
        return MEMORY_E;
    }

    err = (struct wc_error_queue*)XMALLOC(
            sizeof(struct wc_error_queue), wc_error_heap, DYNAMIC_TYPE_LOG);
    if (err == NULL) {
        WOLFSSL_MSG("Unable to create error node for log");
        return MEMORY_E;
    }
    else {
        int sz;

        XMEMSET(err, 0, sizeof(struct wc_error_queue));
        err->heap = wc_error_heap;
        sz = (int)XSTRLEN(buf);
        if (sz > WOLFSSL_MAX_ERROR_SZ - 1) {
            sz = WOLFSSL_MAX_ERROR_SZ - 1;
        }
        if (sz > 0) {
            XMEMCPY(err->error, buf, (size_t)sz);
        }

        sz = (int)XSTRLEN(file);
        if (sz > WOLFSSL_MAX_ERROR_SZ - 1) {
            sz = WOLFSSL_MAX_ERROR_SZ - 1;
        }
        if (sz > 0) {
            XMEMCPY(err->file, file, (size_t)sz);
        }

        err->value = error;
        err->line  = line;

        /* make sure is terminated */
        err->error[WOLFSSL_MAX_ERROR_SZ - 1] = '\0';
        err->file[WOLFSSL_MAX_ERROR_SZ - 1]  = '\0';


        /* since is queue place new node at last of the list */
        if (wc_last_node == NULL) {
            /* case of first node added to queue */
            if (wc_errors != NULL) {
                /* check for unexpected case before over writing wc_errors */
                WOLFSSL_MSG("ERROR in adding new node to logging queue!!");
                /* In the event both wc_last_node and wc_errors are NULL, err
                 * goes unassigned to external wc_errors, wc_last_node. Free
                 * err in this instance since wc_ClearErrorNodes will not
                 */
                XFREE(err, wc_error_heap, DYNAMIC_TYPE_LOG);
            }
            else {
                wc_errors    = err;
                wc_last_node = err;
                wc_current_node = err;
            }
        }
        else {
            wc_last_node->next = err;
            err->prev = wc_last_node;
            wc_last_node = err;

            /* check the case where have read to the end of the queue and the
             * current node to read needs updated */
            if (wc_current_node == NULL) {
                wc_current_node = err;
            }
        }
        wc_errors_count++;
    }
    return 0;
}

/* returns the current index into the queue, which is the node that
 * wc_current_node is pointing to. It can be greater than zero in cases
 * where wc_PullErrorNode() has been called without the node having been
 * removed. */
static int getErrorNodeCurrentIdx(void)
{
    int ret = 0;
    struct wc_error_queue* current;

    current = (struct wc_error_queue*)wc_errors;
    while (current != wc_current_node && current != NULL) {
        current = current->next;
        ret++;
    }

    /* wc_current_node was not found in the list! use index 0 */
    if (current == NULL) {
        ret = 0;
    }
    return ret;
}

static void removeErrorNode(int idx)
{
    struct wc_error_queue* current;

    if (idx == -1) {
        current = wc_last_node;
    }
    else {
        current = (struct wc_error_queue*)wc_errors;
        for (; current != NULL && idx > 0; idx--)
             current = current->next;
    }
    if (current != NULL) {
        if (current->prev != NULL)
            current->prev->next = current->next;
        if (current->next != NULL)
            current->next->prev = current->prev;
        if (wc_last_node == current)
            wc_last_node = current->prev;
        if (wc_errors == current)
            wc_errors = current->next;
        if (wc_current_node == current)
            wc_current_node = current->next;
        XFREE(current, current->heap, DYNAMIC_TYPE_LOG);
        wc_errors_count--;

        /* last node left in list was free'd, reset list head */
        if (wc_errors_count == 0) {
            wc_errors       = NULL;
            wc_last_node    = NULL;
            wc_current_node = NULL;
        }
    }
}

/* Removes the error node at the specified index.
 * idx : if -1 then the most recent node is looked at,
 *       otherwise search through queue for node at the given index starting
 *          from the absolute head wc_errors
 */
void wc_RemoveErrorNode(int idx)
{
    if (ERRQ_LOCK() != 0) {
        WOLFSSL_MSG("Lock debug mutex failed");
        return;
    }

    removeErrorNode(idx);

    ERRQ_UNLOCK();
}

static void clearErrorNodes(void)
{
    struct wc_error_queue* current;
    struct wc_error_queue* next;
    /* free all nodes from error queue (even previously 'pulled' ones) starting
     * at the lists absolute head of wc_errors */

    current = (struct wc_error_queue*)wc_errors;
    while (current != NULL) {
        next = current->next;
        XFREE(current, current->heap, DYNAMIC_TYPE_LOG);
        current = next;
    }

    wc_errors_count = 0;
    wc_errors       = NULL;
    wc_last_node    = NULL;
    wc_current_node = NULL;
}

/* Clears out the list of error nodes.
 */
void wc_ClearErrorNodes(void)
{
    if (ERRQ_LOCK() != 0) {
        WOLFSSL_MSG("Lock debug mutex failed");
        return;
    }

    clearErrorNodes();

    ERRQ_UNLOCK();
}

int wc_SetLoggingHeap(void* h)
{
    if (ERRQ_LOCK() != 0) {
        WOLFSSL_MSG("Lock debug mutex failed");
        return BAD_MUTEX_E;
    }
    wc_error_heap = h;
    ERRQ_UNLOCK();
    return 0;
}

/* frees all nodes in the queue
 *
 * id  this is the thread id
 */
int wc_ERR_remove_state(void)
{
    struct wc_error_queue* current;
    struct wc_error_queue* next;

    if (ERRQ_LOCK() != 0) {
        WOLFSSL_MSG("Lock debug mutex failed");
        return BAD_MUTEX_E;
    }

    /* free all nodes from error queue */
    current = (struct wc_error_queue*)wc_errors;
    while (current != NULL) {
        next = current->next;
        XFREE(current, current->heap, DYNAMIC_TYPE_LOG);
        current = next;
    }

    wc_errors_count = 0;
    wc_errors          = NULL;
    wc_last_node       = NULL;

    ERRQ_UNLOCK();

    return 0;
}

unsigned long wc_PeekErrorNodeLineData(const char **file, int *line,
                                       const char **data, int *flags,
                                       int (*ignore_err)(int err))
{
    int idx;

    WOLFSSL_ENTER("wc_PeekErrorNodeLineData");

/* No data or flags stored - error display only in Nginx. */
    if (data != NULL) {
        *data = "";
    }
    if (flags != NULL) {
        *flags = 0;
    }

    if (ERRQ_LOCK() != 0) {
        WOLFSSL_MSG("Lock debug mutex failed");
        return (unsigned long)(0 - BAD_MUTEX_E);
    }

    idx = getErrorNodeCurrentIdx();
    while (1) {
        int ret = peekErrorNode(idx, file, NULL, line);
        if (ret == WC_NO_ERR_TRACE(BAD_MUTEX_E) ||
            ret == WC_NO_ERR_TRACE(BAD_FUNC_ARG) ||
            ret == WC_NO_ERR_TRACE(BAD_STATE_E)) {
            ERRQ_UNLOCK();
            WOLFSSL_MSG("Issue peeking at error node in queue");
            return 0;
        }
        /* OpenSSL uses positive error codes */
        if (ret < 0) {
            ret = -ret;
        }

        if (ignore_err && ignore_err(ret)) {
          removeErrorNode(idx);
          continue;
        }

        ERRQ_UNLOCK();
        return (unsigned long)ret;
    }
}

int wc_GetErrorNodeErr(void)
{
    int ret;

    WOLFSSL_ENTER("wc_GetErrorNodeErr");

    if (ERRQ_LOCK() != 0) {
        WOLFSSL_MSG("Lock debug mutex failed");
        return (0 - BAD_MUTEX_E);
    }

    ret = pullErrorNode(NULL, NULL, NULL);
    if (ret < 0) {
        if (ret == WC_NO_ERR_TRACE(BAD_STATE_E)) {
            ret = 0; /* no errors in queue */
        }
        else {
            WOLFSSL_MSG("Error with pulling error node!");
            WOLFSSL_LEAVE("wolfSSL_ERR_get_error", ret);
            ret = 0 - ret; /* return absolute value of error */
            /* panic and try to clear out nodes */
            clearErrorNodes();
        }
    }
    else {
        int idx = getErrorNodeCurrentIdx();
        if (idx < 0) {
            WOLFSSL_MSG("Error with getting current index!");
            ret = BAD_STATE_E;
            WOLFSSL_LEAVE("wolfSSL_ERR_get_error", ret);

            /* panic and try to clear out nodes and reset queue state */
            clearErrorNodes();
        }
        else if (idx > 0) {
            idx -= 1;
            removeErrorNode(idx);
        }
        else {
            /* if current idx is 0 then the queue only had one node */
            removeErrorNode(idx);
        }
    }

    ERRQ_UNLOCK();
    return ret;
}

#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM)
/* This callback allows the application to provide a custom error printing
 * function. */
void wc_ERR_print_errors_cb(int (*cb)(const char *str, size_t len, void *u),
                            void *u)
{
    WOLFSSL_ENTER("wc_ERR_print_errors_cb");

    if (cb == NULL) {
        /* Invalid param */
        return;
    }

    if (ERRQ_LOCK() != 0) {
        WOLFSSL_MSG("Lock debug mutex failed");
    }
    else {
        /* free all nodes from error queue and print them to file */
        struct wc_error_queue *current;
        struct wc_error_queue *next;

        current = (struct wc_error_queue *)wc_errors;
        while (current != NULL)
        {
            next = current->next;
            cb(current->error, XSTRLEN(current->error), u);
            XFREE(current, current->heap, DYNAMIC_TYPE_LOG);
            current = next;
        }

        /* set global pointers to match having been freed */
        wc_errors_count = 0;
        wc_errors = NULL;
        wc_last_node = NULL;

        ERRQ_UNLOCK();
    }
}
#endif /* !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) */

#endif /* !ERROR_QUEUE_PER_THREAD */

#else  /* WOLFSSL_HAVE_ERROR_QUEUE */
/* NO ERROR_QUEUE at all */

int wc_LoggingInit(void)
{
    return 0;
}


/* internal function that is called by wolfCrypt_Cleanup */
int wc_LoggingCleanup(void)
{
    return 0;
}

int wc_PeekErrorNode(int idx, const char **file, const char **reason,
        int *line)
{
    (void)idx;
    (void)file;
    (void)reason;
    (void)line;
    WOLFSSL_MSG("Error queue turned off, can not peak nodes");
    return NOT_COMPILED_IN;
}

int wc_PullErrorNode(const char **file, const char **reason, int *line)
{
    (void)file;
    (void)reason;
    (void)line;
    WOLFSSL_MSG("Error queue turned off, can not pull nodes");
    return NOT_COMPILED_IN;
}

int wc_AddErrorNode(int error, int line, char* buf, char* file)
{
    (void)error;
    (void)line;
    (void)buf;
    (void)file;
    WOLFSSL_MSG("Error queue turned off, can not add nodes");
    return NOT_COMPILED_IN;
}

void wc_RemoveErrorNode(int idx)
{
    (void)idx;
    WOLFSSL_MSG("Error queue turned off, can not remove nodes");
}

void wc_ClearErrorNodes(void)
{
    WOLFSSL_MSG("Error queue turned off, can not clear nodes");
}

int wc_SetLoggingHeap(void* h)
{
    (void)h;
    return 0;
}

int wc_ERR_remove_state(void)
{
    return 0;
}

unsigned long wc_PeekErrorNodeLineData(const char **file, int *line,
                                       const char **data, int *flags,
                                       int (*ignore_err)(int err))
{
    WOLFSSL_ENTER("wc_PeekErrorNodeLineData");

    (void)line;
    (void)file;
    (void)ignore_err;
    if (data != NULL) {
        *data = "";
    }
    if (flags != NULL) {
        *flags = 0;
    }
    return (unsigned long)(0 - NOT_COMPILED_IN);
}

int wc_GetErrorNodeErr(void)
{
    WOLFSSL_ENTER("wc_GetErrorNodeErr");
    return (0 - NOT_COMPILED_IN);
}

#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM)
void wc_ERR_print_errors_cb(int (*cb)(const char *str, size_t len, void *u),
                            void *u)
{
    WOLFSSL_ENTER("wc_ERR_print_errors_cb");
    (void)cb;
    (void)u;
}
#endif /* !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) */

#endif /* !WOLFSSL_HAVE_ERROR_QUEUE */

#if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM)
/* empties out the error queue into the file */
static int wc_ERR_dump_to_file (const char *str, size_t len, void *u)
{
    XFILE fp = (XFILE ) u;
    if (fprintf(fp, "%-*.*s\n", (int)len, (int)len, str) < 0)
        return IO_FAILED_E;
    return 0;
}

void wc_ERR_print_errors_fp(XFILE fp)
{
    WOLFSSL_ENTER("wc_ERR_print_errors_fp");

    /* Send all errors to the wc_ERR_dump_to_file function */
    wc_ERR_print_errors_cb(wc_ERR_dump_to_file, fp);
}

#endif /* !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM) */

#endif /* defined(OPENSSL_EXTRA) || defined(DEBUG_WOLFSSL_VERBOSE)
          || defined(HAVE_MEMCACHED) */

/*
 * When using OPENSSL_EXTRA or DEBUG_WOLFSSL_VERBOSE macro then WOLFSSL_ERROR is
 * mapped to new function WOLFSSL_ERROR_LINE which gets the line # and function
 * name where WOLFSSL_ERROR is called at.
 */
#if defined(DEBUG_WOLFSSL) || defined(OPENSSL_ALL) || \
    defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \
    defined(OPENSSL_EXTRA)

#ifdef WOLFSSL_HAVE_ERROR_QUEUE
void WOLFSSL_ERROR_LINE(int error, const char* func, unsigned int line,
        const char* file, void* usrCtx)
#else
void WOLFSSL_ERROR(int error)
#endif
{
#ifdef WOLFSSL_ASYNC_CRYPT
    if (error != WC_NO_ERR_TRACE(WC_PENDING_E))
#endif
    {
        char buffer[WOLFSSL_MAX_ERROR_SZ];

    #ifdef WOLFSSL_HAVE_ERROR_QUEUE
        (void)usrCtx; /* a user ctx for future flexibility */
        (void)func;

        if (ERRQ_LOCK() != 0) {
            WOLFSSL_MSG("Lock debug mutex failed");
            (void)XSNPRINTF(buffer, sizeof(buffer),
                    "wolfSSL error occurred, error = %d", error);
        }
        else {
            #if defined(OPENSSL_EXTRA) && !defined(WOLFCRYPT_ONLY)
            /* If running in compatibility mode do not add want read and
               want right to error queue */
            if (error != WC_NO_ERR_TRACE(WANT_READ) &&
                error != WC_NO_ERR_TRACE(WANT_WRITE)) {
            #endif
            if (error < 0)
                error = error - (2 * error); /* get absolute value */
            (void)XSNPRINTF(buffer, sizeof(buffer),
                    "wolfSSL error occurred, error = %d line:%u file:%s",
                    error, line, file);

            if (wc_AddErrorNode(error, (int)line, buffer, (char*)file) != 0) {
                WOLFSSL_MSG("Error creating logging node");
                /* with void function there is no return here, continue on
                 * to unlock mutex and log what buffer was created. */
            }
            #if defined(OPENSSL_EXTRA) && !defined(WOLFCRYPT_ONLY)
            }
            else {
                (void)XSNPRINTF(buffer, sizeof(buffer),
                    "wolfSSL error occurred, error = %d", error);
            }
            #endif

            ERRQ_UNLOCK();
        }
    #else
        (void)XSNPRINTF(buffer, sizeof(buffer),
                "wolfSSL error occurred, error = %d", error);
    #endif

    #ifdef DEBUG_WOLFSSL
        if (loggingEnabled)
            wolfssl_log(ERROR_LOG, NULL, 0, buffer);
    #endif
    }
}

void WOLFSSL_ERROR_MSG(const char* msg)
{
#ifdef DEBUG_WOLFSSL
    if (loggingEnabled)
        wolfssl_log(ERROR_LOG, NULL, 0, msg);
#else
    (void)msg;
#endif
}

#endif  /* DEBUG_WOLFSSL || WOLFSSL_NGINX || WOLFSSL_HAPROXY */

#ifdef WOLFSSL_DEBUG_TRACE_ERROR_CODES

#ifndef WOLFSSL_DEBUG_TRACE_ERROR_CODES_INIT_STATE
    #define WOLFSSL_DEBUG_TRACE_ERROR_CODES_INIT_STATE 1
#endif

#ifdef WOLFSSL_ATOMIC_OPS
static wolfSSL_Atomic_Int wc_debug_trace_error_codes_state =
    WOLFSSL_ATOMIC_INITIALIZER(WOLFSSL_DEBUG_TRACE_ERROR_CODES_INIT_STATE);
#else
static int wc_debug_trace_error_codes_state =
    WOLFSSL_DEBUG_TRACE_ERROR_CODES_INIT_STATE;
#endif

int wc_debug_trace_error_codes_enabled(void) {
    return WOLFSSL_ATOMIC_LOAD(wc_debug_trace_error_codes_state);
}

int wc_debug_trace_error_codes_set(int state) {
    return wolfSSL_Atomic_Int_Exchange(&wc_debug_trace_error_codes_state,
                                       state);
}

#endif /* WOLFSSL_DEBUG_TRACE_ERROR_CODES */

#ifdef WOLFSSL_DEBUG_BACKTRACE_ERROR_CODES

#ifdef WOLFSSL_LINUXKM

int wc_backtrace_render(void) {
    dump_stack();
    return 0;
}

#else /* !WOLFSSL_LINUXKM */

#include <backtrace-supported.h>

#if BACKTRACE_SUPPORTED != 1
    #error WOLFSSL_DEBUG_BACKTRACE_ERROR_CODES is defined but BACKTRACE_SUPPORTED is 0.
#endif

#if !defined(WOLFSSL_MUTEX_INITIALIZER) && defined(WOLFSSL_NO_ATOMICS)
    #error WOLFSSL_DEBUG_BACKTRACE_ERROR_CODES requires WOLFSSL_MUTEX_INITIALIZER or wolfSSL_Atomic_Ints.
#endif

#include <backtrace.h>

static int backtrace_callback(void *data, uintptr_t pc, const char *filename,
                              int lineno, const char *function)
{
    if (function == NULL)
        return 0;
    /* the first callback is for the call to wc_print_backtrace() -- skip it. */
    if (*(int *)data == 0) {
        *(int *)data = 1;
        return 0;
    }
    WOLFSSL_DEBUG_PRINTF("    #%d %p in %s %s:%d\n", (*(int *)data)++,
                         (void *)pc, function, filename, lineno);
    return 0;
}

static void backtrace_error(void *data, const char *msg, int errnum) {
    (void)data;
    WOLFSSL_DEBUG_PRINTF("ERR TRACE: error %d while backtracing: %s",
                         errnum, msg);
}

static void backtrace_creation_error(void *data, const char *msg, int errnum) {
    (void)data;
    WOLFSSL_DEBUG_PRINTF("ERR TRACE: internal error %d "
            "while initializing backtrace facility: %s", errnum, msg);
}

static int backtrace_init(struct backtrace_state **backtrace_state) {
#ifdef WOLFSSL_MUTEX_INITIALIZER
    static wolfSSL_Mutex backtrace_create_state_mutex =
        WOLFSSL_MUTEX_INITIALIZER(backtrace_create_state_mutex);
    if (wc_LockMutex(&backtrace_create_state_mutex) != 0)
        return -1;
#elif defined(WOLFSSL_ATOMIC_OPS)
    static wolfSSL_Atomic_Int init_count = 0;
    if (wolfSSL_Atomic_Int_FetchAdd(&init_count, 1) != 1)
        return -1;
#endif
    if (*backtrace_state == NULL) {
        /* passing a NULL filename to backtrace_create_state() tells
         * libbacktrace to use a target-specific strategy to determine the
         * executable.  "libbacktrace supports ELF, PE/COFF, Mach-O, and XCOFF
         * executables with DWARF debugging information.  In other words, it
         * supports GNU/Linux, *BSD, macOS, Windows, and AIX."
         */
        *backtrace_state = backtrace_create_state(
            NULL, 0, backtrace_creation_error, NULL);
    }
#ifdef WOLFSSL_MUTEX_INITIALIZER
    wc_UnLockMutex(&backtrace_create_state_mutex);
#endif
    if (*backtrace_state == NULL)
        return -1;
    return 0;
}

int wc_backtrace_render(void) {
    static wolfSSL_Mutex backtrace_mutex
        WOLFSSL_MUTEX_INITIALIZER_CLAUSE(backtrace_mutex);
    static struct backtrace_state *backtrace_state = NULL;
    int depth = 0;
    int ret;

#ifndef WOLFSSL_MUTEX_INITIALIZER
    static wolfSSL_Atomic_Int init_count = 0;
    if (init_count != 1) {
        int cur_init_count = wolfSSL_Atomic_Int_FetchSub(&init_count, 1);
        if (cur_init_count != 0) {
            (void)wolfSSL_Atomic_Int_FetchAdd(&init_count, 1);
            return WC_NO_ERR_TRACE(DEADLOCK_AVERTED_E);
        }
        ret = wc_InitMutex(&backtrace_mutex);
        if (ret != 0)
            return ret;
        /* set init_count to 1, race-free: (-1) - (0-2) = 1 */
        (void)wolfSSL_Atomic_Int_FetchSub(&init_count, cur_init_count - 2);
    }
#endif

    /* backtrace_state can't be shared between threads even when
     * BACKTRACE_SUPPORTS_THREADS == 1, so we serialize the render op.  this
     * helpfully mutexes the initialization too.
     */
    ret = wc_LockMutex(&backtrace_mutex);
    if (ret != 0)
        return ret;

    if (backtrace_state == NULL) {
        if (backtrace_init(&backtrace_state) < 0) {
            wc_UnLockMutex(&backtrace_mutex);
            return WC_NO_ERR_TRACE(BAD_STATE_E);
        }
    }

    /* note that the optimizer can produce misleading backtraces, even with
     * -funwind-tables.  in contrast, the macro-generated "ERR TRACE" message
     * from WC_ERR_TRACE() always accurately identifies the error code point.
     */
    backtrace_full(backtrace_state, 0, backtrace_callback, backtrace_error,
                   (void *)&depth);

    wc_UnLockMutex(&backtrace_mutex);

    return 0;
}
#endif /* !WOLFSSL_LINUXKM */

#endif /* WOLFSSL_DEBUG_BACKTRACE_ERROR_CODES */