-
Notifications
You must be signed in to change notification settings - Fork 100
/
OTLog.cpp
1660 lines (1366 loc) · 47.3 KB
/
OTLog.cpp
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
/************************************************************
*
* OTLog.cpp
*
*/
/************************************************************
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
* OPEN TRANSACTIONS
*
* Financial Cryptography and Digital Cash
* Library, Protocol, API, Server, CLI, GUI
*
* -- Anonymous Numbered Accounts.
* -- Untraceable Digital Cash.
* -- Triple-Signed Receipts.
* -- Cheques, Vouchers, Transfers, Inboxes.
* -- Basket Currencies, Markets, Payment Plans.
* -- Signed, XML, Ricardian-style Contracts.
* -- Scripted smart contracts.
*
* Copyright (C) 2010-2013 by "Fellow Traveler" (A pseudonym)
*
* EMAIL:
* FellowTraveler@rayservers.net
*
* BITCOIN: 1NtTPVVjDsUfDWybS4BwvHpG2pdS9RnYyQ
*
* KEY FINGERPRINT (PGP Key in license file):
* 9DD5 90EB 9292 4B48 0484 7910 0308 00ED F951 BB8E
*
* OFFICIAL PROJECT WIKI(s):
* https://github.com/FellowTraveler/Moneychanger
* https://github.com/FellowTraveler/Open-Transactions/wiki
*
* WEBSITE:
* http://www.OpenTransactions.org/
*
* Components and licensing:
* -- Moneychanger..A Java client GUI.....LICENSE:.....GPLv3
* -- otlib.........A class library.......LICENSE:...LAGPLv3
* -- otapi.........A client API..........LICENSE:...LAGPLv3
* -- opentxs/ot....Command-line client...LICENSE:...LAGPLv3
* -- otserver......Server Application....LICENSE:....AGPLv3
* Github.com/FellowTraveler/Open-Transactions/wiki/Components
*
* All of the above OT components were designed and written by
* Fellow Traveler, with the exception of Moneychanger, which
* was contracted out to Vicky C (bitcointrader4@gmail.com).
* The open-source community has since actively contributed.
*
* -----------------------------------------------------
*
* LICENSE:
* This program is free software: you can redistribute it
* and/or modify it under the terms of the GNU Affero
* General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* ADDITIONAL PERMISSION under the GNU Affero GPL version 3
* section 7: (This paragraph applies only to the LAGPLv3
* components listed above.) If you modify this Program, or
* any covered work, by linking or combining it with other
* code, such other code is not for that reason alone subject
* to any of the requirements of the GNU Affero GPL version 3.
* (==> This means if you are only using the OT API, then you
* don't have to open-source your code--only your changes to
* Open-Transactions itself must be open source. Similar to
* LGPLv3, except it applies to software-as-a-service, not
* just to distributing binaries.)
*
* Extra WAIVER for OpenSSL, Lucre, and all other libraries
* used by Open Transactions: This program is released under
* the AGPL with the additional exemption that compiling,
* linking, and/or using OpenSSL is allowed. The same is true
* for any other open source libraries included in this
* project: complete waiver from the AGPL is hereby granted to
* compile, link, and/or use them with Open-Transactions,
* according to their own terms, as long as the rest of the
* Open-Transactions terms remain respected, with regard to
* the Open-Transactions code itself.
*
* Lucre License:
* This code is also "dual-license", meaning that Ben Lau-
* rie's license must also be included and respected, since
* the code for Lucre is also included with Open Transactions.
* See Open-Transactions/src/otlib/lucre/LUCRE_LICENSE.txt
* The Laurie requirements are light, but if there is any
* problem with his license, simply remove the Lucre code.
* Although there are no other blind token algorithms in Open
* Transactions (yet. credlib is coming), the other functions
* will continue to operate.
* See Lucre on Github: https://github.com/benlaurie/lucre
* -----------------------------------------------------
* You should have received a copy of the GNU Affero General
* Public License along with this program. If not, see:
* http://www.gnu.org/licenses/
*
* If you would like to use this software outside of the free
* software license, please contact FellowTraveler.
* (Unfortunately many will run anonymously and untraceably,
* so who could really stop them?)
*
* DISCLAIMER:
* This program is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU Affero General Public License for
* more details.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Darwin)
iQIcBAEBAgAGBQJRSsfJAAoJEAMIAO35UbuOQT8P/RJbka8etf7wbxdHQNAY+2cC
vDf8J3X8VI+pwMqv6wgTVy17venMZJa4I4ikXD/MRyWV1XbTG0mBXk/7AZk7Rexk
KTvL/U1kWiez6+8XXLye+k2JNM6v7eej8xMrqEcO0ZArh/DsLoIn1y8p8qjBI7+m
aE7lhstDiD0z8mwRRLKFLN2IH5rAFaZZUvj5ERJaoYUKdn4c+RcQVei2YOl4T0FU
LWND3YLoH8naqJXkaOKEN4UfJINCwxhe5Ke9wyfLWLUO7NamRkWD2T7CJ0xocnD1
sjAzlVGNgaFDRflfIF4QhBx1Ddl6wwhJfw+d08bjqblSq8aXDkmFA7HeunSFKkdn
oIEOEgyj+veuOMRJC5pnBJ9vV+7qRdDKQWaCKotynt4sWJDGQ9kWGWm74SsNaduN
TPMyr9kNmGsfR69Q2Zq/FLcLX/j8ESxU+HYUB4vaARw2xEOu2xwDDv6jt0j3Vqsg
x7rWv4S/Eh18FDNDkVRChiNoOIilLYLL6c38uMf1pnItBuxP3uhgY6COm59kVaRh
nyGTYCDYD2TK+fI9o89F1297uDCwEJ62U0Q7iTDp5QuXCoxkPfv8/kX6lS6T3y9G
M9mqIoLbIQ1EDntFv7/t6fUTS2+46uCrdZWbQ5RjYXdrzjij02nDmJAm2BngnZvd
kamH0Y/n11lCvo1oQxM+
=uSzz
-----END PGP SIGNATURE-----
**************************************************************/
#include "stdafx.hpp"
#include "OTLog.hpp"
#include "OTPaths.hpp"
#include "util/stacktrace.h"
#include "opentxs/core/Version.hpp"
#include <mutex>
#ifndef _WIN32
#include <cerrno>
#endif
#include <fstream>
#include <iostream>
#ifdef _WIN32
#include <Shlobj.h>
#include <direct.h>
#else
#include <libgen.h>
#include <unistd.h>
#endif
#ifdef __APPLE__
#include "TargetConditionals.h"
#endif
#ifdef TARGET_OS_MAC
#include <mach-o/dyld.h>
#include <limits.h>
#endif
#define LOG_DEQUE_SIZE 1024
extern "C" {
#ifdef _WIN32
#include <sys/timeb.h>
// For signal handling in Windows.
LONG Win32FaultHandler(struct _EXCEPTION_POINTERS* ExInfo);
void LogStackFrames(void* FaultAdress, char*);
#else // else if NOT _WIN32
// These added for the signal handling:
//
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#ifndef __USE_GNU
#define __USE_GNU
#endif
// This shitty apple section is for struct sigcontext for the signal handling.
#if defined(__APPLE__)
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE 600
#endif
// Fucking Apple!
struct sigcontext
{
// cppcheck-suppress unusedStructMember
int32_t eip;
};
#endif // defined __APPLE__
#if defined(ANDROID)
#ifndef ucontext_h_seen
#define ucontext_h_seen
#include <asm/sigcontext.h> /* for sigcontext */
#include <asm/signal.h> /* for stack_t */
typedef struct ucontext
{
uint64_t uc_flags;
struct ucontext* uc_link;
stack_t uc_stack;
struct sigcontext uc_mcontext;
uint64_t uc_sigmask;
} ucontext_t;
#endif // ucontext_h_seen
#else // Not ANDROID
#include <signal.h>
#include <ucontext.h>
#include <wordexp.h>
#include <execinfo.h>
#endif
#include <sys/resource.h>
//#endif
#endif // not _WIN32
#include <sys/stat.h>
} // extern C
#ifdef ANDROID
#include <android/log.h>
#endif
#define LOGFILE_PRE "log-"
#define LOGFILE_EXT ".log"
#define GLOBAL_LOGNAME "init"
#define GLOBAL_LOGFILE "init.log"
// OTLog Static Variables and Constants.
namespace opentxs
{
OTLog* OTLog::pLogger = nullptr;
const OTString OTLog::m_strVersion = OPENTXS_VERSION_STRING;
const OTString OTLog::m_strPathSeparator = "/";
OTLOG_IMPORT OTLogStream otErr(-1); // logs using otErr << )
OTLOG_IMPORT OTLogStream otInfo(2); // logs using OTLog::vOutput(2)
OTLOG_IMPORT OTLogStream otOut(0); // logs using OTLog::vOutput(0)
OTLOG_IMPORT OTLogStream otWarn(1); // logs using OTLog::vOutput(1)
OTLOG_IMPORT OTLogStream otLog3(3); // logs using OTLog::vOutput(3)
OTLOG_IMPORT OTLogStream otLog4(4); // logs using OTLog::vOutput(4)
OTLOG_IMPORT OTLogStream otLog5(5); // logs using OTLog::vOutput(5)
OTLogStream::OTLogStream(int _logLevel)
: std::ostream(this)
, logLevel(_logLevel)
, next(0)
, pBuffer(new char[1024])
{
}
OTLogStream::~OTLogStream()
{
delete[] pBuffer;
pBuffer = nullptr;
}
int OTLogStream::overflow(int c)
{
pBuffer[next++] = c;
if (c != '\n' && next < 1000) {
return 0;
}
pBuffer[next++] = '\0';
next = 0;
if (logLevel < 0) {
OTLog::Error(pBuffer);
return 0;
}
OTLog::Output(logLevel, pBuffer);
return 0;
}
// OTLog Init, must run this before using any OTLog function.
// static
bool OTLog::Init(const OTString& strThreadContext, const int32_t& nLogLevel)
{
if (nullptr == pLogger) {
pLogger = new OTLog();
pLogger->m_bInitialized = false;
}
if (strThreadContext.Compare(GLOBAL_LOGNAME)) return false;
if (!pLogger->m_bInitialized) {
pLogger->logDeque = std::deque<OTString*>();
pLogger->m_strThreadContext = strThreadContext;
pLogger->m_nLogLevel = nLogLevel;
if (!strThreadContext.Exists() ||
strThreadContext.Compare("")) // global
{
pLogger->m_strLogFileName = GLOBAL_LOGFILE;
}
else // not global
{
pLogger->m_strLogFileName.Format(
"%s%s%s", LOGFILE_PRE, strThreadContext.Get(), LOGFILE_EXT);
OTSettings config(OTPaths::GlobalConfigFile());
config.Reset();
if (!config.Load()) {
return false;
};
bool bIsNew(false);
if (!config.CheckSet_str("logfile", strThreadContext,
pLogger->m_strLogFileName,
pLogger->m_strLogFileName, bIsNew)) {
return false;
}
if (!config.Save()) {
return false;
};
config.Reset();
}
#ifdef ANDROID
if (OTPaths::HomeFolder().Exists())
#endif
if (!OTPaths::AppendFile(pLogger->m_strLogFilePath,
OTPaths::AppDataFolder(),
pLogger->m_strLogFileName)) {
return false;
};
pLogger->m_bInitialized = true;
// Set the new log-assert function pointer.
Assert* pLogAssert = new Assert(OTLog::logAssert);
std::swap(pLogAssert, Assert::s_pAssert);
delete pLogAssert;
pLogAssert = nullptr;
return true;
}
else {
return false;
}
}
// static
bool OTLog::IsInitialized()
{
return nullptr != pLogger && pLogger->m_bInitialized;
}
// static
bool OTLog::Cleanup()
{
if (nullptr != pLogger) {
delete pLogger;
pLogger = nullptr;
return true;
}
return false;
}
// static
bool OTLog::CheckLogger(OTLog* pLogger)
{
if (nullptr != pLogger && pLogger->m_bInitialized) return true;
OT_FAIL;
}
// OTLog Constants.
// Compiled into OTLog:
const char* OTLog::Version()
{
return OTLog::GetVersion().Get();
}
const OTString& OTLog::GetVersion()
{
return m_strVersion;
}
const char* OTLog::PathSeparator()
{
return OTLog::GetPathSeparator().Get();
}
const OTString& OTLog::GetPathSeparator()
{
return m_strPathSeparator;
}
// Set in constructor:
const OTString& OTLog::GetThreadContext()
{
return pLogger->m_strThreadContext;
}
const char* OTLog::LogFilePath()
{
return OTLog::GetLogFilePath().Get();
}
const OTString& OTLog::GetLogFilePath()
{
return pLogger->m_strLogFilePath;
}
// static
int32_t OTLog::LogLevel()
{
if (nullptr != pLogger)
return pLogger->m_nLogLevel;
else
return 0;
}
// static
bool OTLog::SetLogLevel(const int32_t& nLogLevel)
{
if (nullptr == pLogger) {
OT_FAIL;
}
else {
pLogger->m_nLogLevel = nLogLevel;
return true;
}
}
// OTLog Functions
// If there's no logfile, then send it to stderr.
// (So we can still see it on the screen, but it doesn't interfere with any
// command line utilities who might otherwise interpret it as their own input,
// if I was actually writing to stdout.)
//
// static
bool OTLog::LogToFile(const OTString& strOutput)
{
// We now do this either way.
{
std::cerr << strOutput;
std::cerr.flush();
}
// now log to file, if we can.
bool bHaveLogger(false);
if (nullptr != pLogger)
if (pLogger->IsInitialized()) bHaveLogger = true;
// lets check if we are Initialized in this context
if (bHaveLogger) CheckLogger(OTLog::pLogger);
bool bSuccess = false;
if (bHaveLogger) {
// Append to logfile
if ((strOutput.Exists()) &&
(OTLog::pLogger->m_strLogFilePath.Exists())) {
std::ofstream logfile;
logfile.open(OTLog::LogFilePath(), std::ios::app);
if (!logfile.fail()) {
logfile << strOutput;
logfile.close();
bSuccess = true;
}
}
}
return bSuccess;
}
OTString OTLog::GetMemlogAtIndex(int32_t nIndex)
{
// lets check if we are Initialized in this context
CheckLogger(OTLog::pLogger);
uint32_t uIndex = static_cast<uint32_t>(nIndex);
if ((nIndex < 0) || (uIndex >= OTLog::pLogger->logDeque.size())) {
otErr << __FUNCTION__ << ": index out of bounds: " << nIndex << "\n";
return "";
}
if (nullptr != OTLog::pLogger->logDeque.at(uIndex))
; // check for null
else
OT_FAIL;
const OTString strLogEntry = *OTLog::pLogger->logDeque.at(uIndex);
if (strLogEntry.Exists())
return strLogEntry;
else
return "";
}
// We keep 1024 logs in memory, to make them available via the API.
int32_t OTLog::GetMemlogSize()
{
// lets check if we are Initialized in this context
CheckLogger(OTLog::pLogger);
return static_cast<int32_t>(OTLog::pLogger->logDeque.size());
}
OTString OTLog::PeekMemlogFront()
{
// lets check if we are Initialized in this context
CheckLogger(OTLog::pLogger);
if (OTLog::pLogger->logDeque.size() <= 0) return nullptr;
if (nullptr != OTLog::pLogger->logDeque.front())
; // check for null
else
OT_FAIL;
const OTString strLogEntry = *OTLog::pLogger->logDeque.front();
if (strLogEntry.Exists())
return strLogEntry;
else
return "";
}
OTString OTLog::PeekMemlogBack()
{
// lets check if we are Initialized in this context
CheckLogger(OTLog::pLogger);
if (OTLog::pLogger->logDeque.size() <= 0) return nullptr;
if (nullptr != OTLog::pLogger->logDeque.back())
; // check for null
else
OT_FAIL;
const OTString strLogEntry = *OTLog::pLogger->logDeque.back();
if (strLogEntry.Exists())
return strLogEntry;
else
return "";
}
// static
bool OTLog::PopMemlogFront()
{
// lets check if we are Initialized in this context
CheckLogger(OTLog::pLogger);
if (OTLog::pLogger->logDeque.size() <= 0) return false;
OTString* strLogFront = OTLog::pLogger->logDeque.front();
if (nullptr != strLogFront) delete strLogFront;
strLogFront = nullptr;
OTLog::pLogger->logDeque.pop_front();
return true;
}
// static
bool OTLog::PopMemlogBack()
{
// lets check if we are Initialized in this context
CheckLogger(OTLog::pLogger);
if (OTLog::pLogger->logDeque.size() <= 0) return false;
OTString* strLogBack = OTLog::pLogger->logDeque.back();
if (nullptr != strLogBack) delete strLogBack;
strLogBack = nullptr;
OTLog::pLogger->logDeque.pop_back();
return true;
}
// static
bool OTLog::PushMemlogFront(const OTString& strLog)
{
// lets check if we are Initialized in this context
CheckLogger(OTLog::pLogger);
OT_ASSERT(strLog.Exists());
OTLog::pLogger->logDeque.push_front(new OTString(strLog));
if (OTLog::pLogger->logDeque.size() > LOG_DEQUE_SIZE) {
OTLog::PopMemlogBack(); // We start removing from the back when it
// reaches this size.
}
return true;
}
// static
bool OTLog::PushMemlogBack(const OTString& strLog)
{
// lets check if we are Initialized in this context
CheckLogger(OTLog::pLogger);
OT_ASSERT(strLog.Exists());
OTLog::pLogger->logDeque.push_back(new OTString(strLog));
return true;
}
// static
bool OTLog::SleepSeconds(int64_t lSeconds)
{
#ifdef _WIN32
Sleep(static_cast<DWORD>(1000 * lSeconds));
#else
sleep(lSeconds);
#endif
return true;
}
// static
bool OTLog::SleepMilliseconds(int64_t lMilliseconds)
{
#ifdef _WIN32
Sleep(static_cast<DWORD>(lMilliseconds));
#else
usleep(lMilliseconds * 1000);
#endif
return true;
}
// This function is for things that should NEVER happen.
// In fact you should never even call it -- use the OT_ASSERT() macro instead.
// This Function is now only for logging, you
// static private
size_t OTLog::logAssert(const char* szFilename, size_t nLinenumber,
const char* szMessage)
{
if (nullptr != szMessage) {
#ifndef ANDROID // if NOT android
std::cerr << szMessage << "\n";
LogToFile(szMessage);
LogToFile("\n");
#else // if Android
__android_log_write(ANDROID_LOG_FATAL, "OT Assert (or Fail)",
szMessage);
#endif
print_stacktrace();
}
if ((nullptr != szFilename)) {
#ifndef ANDROID // if NOT android
// Pass it to LogToFile, as this always logs.
//
OTString strTemp;
strTemp.Format("\nOT_ASSERT in %s at line %d\n", szFilename,
nLinenumber);
LogToFile(strTemp.Get());
#else // if Android
OTString strAndroidAssertMsg;
strAndroidAssertMsg.Format("\nOT_ASSERT in %s at line %d\n", szFilename,
nLinenumber);
__android_log_write(ANDROID_LOG_FATAL, "OT Assert",
(const char*)strAndroidAssertMsg.Get());
#endif
}
print_stacktrace();
return 1; // normal
}
// For normal output. The higher the verbosity, the less important the message.
// (Verbose level 0 ALWAYS logs.) Currently goes to stdout.
void OTLog::Output(int32_t nVerbosity, const char* szOutput)
{
bool bHaveLogger(false);
if (nullptr != pLogger)
if (pLogger->IsInitialized()) bHaveLogger = true;
// lets check if we are Initialized in this context
if (bHaveLogger) CheckLogger(OTLog::pLogger);
// If log level is 0, and verbosity of this message is 2, don't bother
// logging it.
// if (nVerbosity > OTLog::__CurrentLogLevel || (nullptr == szOutput))
if ((nVerbosity > LogLevel()) || (nullptr == szOutput) ||
(LogLevel() == (-1)))
return;
// We store the last 1024 logs so programmers can access them via the API.
if (bHaveLogger) OTLog::PushMemlogFront(szOutput);
#ifndef ANDROID // if NOT android
LogToFile(szOutput);
#else // if IS Android
/*
typedef enum android_LogPriority {
ANDROID_LOG_UNKNOWN = 0,
ANDROID_LOG_DEFAULT, // only for SetMinPriority()
ANDROID_LOG_VERBOSE,
ANDROID_LOG_DEBUG,
ANDROID_LOG_INFO,
ANDROID_LOG_WARN,
ANDROID_LOG_ERROR,
ANDROID_LOG_FATAL,
ANDROID_LOG_SILENT, // only for SetMinPriority(); must be last
} android_LogPriority;
*/
switch (nVerbosity) {
case 0:
case 1:
__android_log_write(ANDROID_LOG_INFO, "OT Output", szOutput);
break;
case 2:
case 3:
__android_log_write(ANDROID_LOG_DEBUG, "OT Debug", szOutput);
break;
case 4:
case 5:
__android_log_write(ANDROID_LOG_VERBOSE, "OT Verbose", szOutput);
break;
default:
__android_log_write(ANDROID_LOG_UNKNOWN, "OT Unknown", szOutput);
break;
}
#endif
}
// the vOutput is to avoid name conflicts.
void OTLog::vOutput(int32_t nVerbosity, const char* szOutput, ...)
{
bool bHaveLogger(false);
if (nullptr != pLogger)
if (pLogger->IsInitialized()) bHaveLogger = true;
// lets check if we are Initialized in this context
if (bHaveLogger) CheckLogger(OTLog::pLogger);
// If log level is 0, and verbosity of this message is 2, don't bother
// logging it.
if (((0 != LogLevel()) && (nVerbosity > LogLevel())) ||
(nullptr == szOutput))
return;
va_list args;
va_start(args, szOutput);
std::string strOutput;
const bool bFormatted = OTString::vformat(szOutput, &args, strOutput);
va_end(args);
if (bFormatted)
OTLog::Output(nVerbosity, strOutput.c_str());
else
OT_FAIL;
return;
}
// the vError name is to avoid name conflicts
void OTLog::vError(const char* szError, ...)
{
bool bHaveLogger(false);
if (nullptr != pLogger)
if (pLogger->IsInitialized()) bHaveLogger = true;
// lets check if we are Initialized in this context
if (bHaveLogger) CheckLogger(OTLog::pLogger);
if ((nullptr == szError)) return;
va_list args;
va_start(args, szError);
std::string strOutput;
const bool bFormatted = OTString::vformat(szError, &args, strOutput);
va_end(args);
if (bFormatted)
OTLog::Error(strOutput.c_str());
else
OT_FAIL;
}
// An error has occurred, that somehow doesn't match the Assert or Output
// functions.
// So use this one instead. This ALWAYS logs and currently it all goes to
// stderr.
void OTLog::Error(const char* szError)
{
bool bHaveLogger(false);
if (nullptr != pLogger)
if (pLogger->IsInitialized()) bHaveLogger = true;
// lets check if we are Initialized in this context
if (bHaveLogger) CheckLogger(OTLog::pLogger);
if ((nullptr == szError)) return;
// We store the last 1024 logs so programmers can access them via the API.
if (bHaveLogger) OTLog::PushMemlogFront(szError);
#ifndef ANDROID // if NOT android
LogToFile(szError);
#else // if Android
__android_log_write(ANDROID_LOG_ERROR, "OT Error", szError);
#endif
}
// NOTE: if you have problems compiling on certain platforms, due to the use
// of errno, then just use preprocessor directives to carve those portions out
// of this function, replacing with a message about the unavailability of errno.
//
// static
void OTLog::Errno(const char* szLocation) // stderr
{
bool bHaveLogger(false);
if (nullptr != pLogger)
if (pLogger->IsInitialized()) bHaveLogger = true;
// lets check if we are Initialized in this context
if (bHaveLogger) CheckLogger(OTLog::pLogger);
const int32_t errnum = errno;
char buf[128];
buf[0] = '\0';
int32_t nstrerr = 0;
char* szErrString = nullptr;
//#if((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) &&
//!defined(_GNU_SOURCE))
#if defined(_GNU_SOURCE) && defined(__linux__) && !defined(ANDROID)
szErrString = strerror_r(errnum, buf, 127);
#elif(_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600)
nstrerr = strerror_r(errnum, buf,
127); // (strerror_r is threadsafe version of strerror)
#endif
const char* szFunc = "OTLog::Errno";
const char* sz_location = (nullptr == szLocation) ? "" : szLocation;
if (nullptr == szErrString) szErrString = buf;
if (0 == nstrerr)
otErr << szFunc << " " << sz_location << ": errno " << errnum << ": "
<< (szErrString[0] != '\0' ? szErrString : "") << ".\n";
else
otErr << szFunc << " " << sz_location << ": errno: " << errnum
<< ". (Unable to retrieve error string for that number.)\n";
}
// String Helpers
bool OTLog::StringFill(OTString& out_strString, const char* szString,
int32_t iLength, const char* szAppend)
{
std::string strString(szString);
if (nullptr != szAppend) strString.append(szAppend);
for (; (static_cast<int32_t>(strString.length()) < iLength);
strString.append(" "))
;
out_strString.Set(strString.c_str());
return true;
}
// SIGNALS
//
// To get the most mileage out of this signal handler,
// compile it with the options: -g -rdynamic
//
// Signal Handler
//
//
void ot_terminate(void);
namespace
{
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4800) // warning C4800: forcing constant value.
#endif
// invoke set_terminate as part of global constant initialization
static const bool SET_TERMINATE = std::set_terminate(ot_terminate);
#ifdef _MSC_VER
#pragma warning(pop)
#endif
}
// This is our custom std::terminate(). Also called for uncaught exceptions.
void ot_terminate()
{
try {
// try once to re-throw currently active exception
static bool tried_throw = false;
if (!tried_throw) {
tried_throw = true;
throw;
}
}
catch (const std::exception& e) {
std::cerr << "ot_terminate: " << __FUNCTION__
<< " caught unhandled exception. type: " << typeid(e).name()
<< " what(): " << e.what() << std::endl;
}
catch (...) {
std::cerr << "ot_terminate: " << __FUNCTION__
<< " caught unknown/unhandled exception." << std::endl;
}
// UNIX
#if !defined(_WIN32) && !defined(ANDROID) // we don't have to deal with
// mangled_names on windows. (well I'm
// not going to attempt to.)
void* array[50];
int32_t size = backtrace(array, 50);
char** messages = backtrace_symbols(array, size);
// skip first stack frame (points here)
for (int32_t i = 1; i < size && messages != nullptr; ++i) {
char* mangled_name = 0, *offset_begin = 0, *offset_end = 0;
// find parantheses and +address offset surrounding mangled name
for (char* p = messages[i]; *p; ++p) {
if (*p == '(') {
mangled_name = p;
}
else if (*p == '+') {
offset_begin = p;
}
else if (*p == ')') {
offset_end = p;
break;
}
}
// if the line could be processed, attempt to demangle the symbol
if (mangled_name && offset_begin && offset_end &&
mangled_name < offset_begin) {
*mangled_name++ = '\0';
*offset_begin++ = '\0';
*offset_end++ = '\0';
int32_t status;