Stroika Library 3.0d25
 
Loading...
Searching...
No Matches
Trace.cpp
1/*
2 * Copyright(c) Sophist Solutions, Inc. 1990-2026. All rights reserved
3 */
4#include "Stroika/Foundation/StroikaPreComp.h"
5
6#include <cmath>
7#include <cstdarg>
8#include <cstdio>
9#include <fstream>
10#include <map>
11#include <mutex>
12
15#include "Stroika/Foundation/Characters/LineEndings.h"
20#include "Stroika/Foundation/Execution/Common.h"
21#include "Stroika/Foundation/Execution/Module.h"
22#include "Stroika/Foundation/Execution/Process.h"
24#include "Stroika/Foundation/Memory/Common.h"
28
29#if qStroika_Foundation_Debug_TraceToFile
32#endif
33
34using namespace Stroika::Foundation;
35
36using namespace Characters;
37using namespace Debug;
38using namespace Execution;
39
41
42using Debug::Private_::Emitter;
43
44/*
45 * TODO:
46 *
47 * @todo The buffering code here maybe now correct, but isn't simple/clear, so rewrite/improve...
48 * -- LGP 2011-10-03
49 */
50
51CompileTimeFlagChecker_SOURCE (Stroika::Foundation::Debug, qTraceToFile, qStroika_Foundation_Debug_TraceToFile);
52CompileTimeFlagChecker_SOURCE (Stroika::Foundation::Debug, qDefaultTracingOn, qStroika_Foundation_Debug_DefaultTracingOn);
53
54namespace {
55 // This is MOSTLY to remove NEWLINES from the MIDDLE of a message - replace with kBadChar.
56 const char kBadChar_ = ' ';
57 void SquishBadCharacters_ (string* s) noexcept
58 {
60 size_t end = s->length ();
61 // ignore last 2 in case crlf
62 if (end > 2) {
63 end -= 2;
64 }
65 for (size_t i = 0; i < end; ++i) {
66 if ((*s)[i] == '\n' or (*s)[i] == '\r') {
67 (*s)[i] = kBadChar_;
68 }
69 }
70 }
71 void SquishBadCharacters_ (wstring* s) noexcept
72 {
74 size_t end = s->length ();
75 // ignore last 2 in case crlf
76 if (end > 2) {
77 end -= 2;
78 }
79 for (size_t i = 0; i < end; ++i) {
80 if ((*s)[i] == '\n' or (*s)[i] == '\r') {
81 (*s)[i] = kBadChar_;
82 }
83 }
84 }
85}
86
87namespace {
88#if qStroika_Foundation_Debug_DefaultTracingOn
89 thread_local unsigned int tTraceContextDepth_{0}; // no need for atomic access because thread_local
90#endif
91
92 // Declared HERE instead of the template so they get shared across TYPE values for CHARTYPE
93 Thread::IDType sMainThread_ = Execution::Thread::GetCurrentThreadID ();
94}
95
96/*
97 ********************************************************************************
98 ******************************* Debug::Private_::Emitter ***********************
99 ********************************************************************************
100 */
101template <typename CHARTYPE>
102inline void Debug::Private_::Emitter::EmitUnadornedText (const CHARTYPE* p)
103{
104 DoEmit_ (p);
105}
106
107/*
108 ********************************************************************************
109 ************************* Debug::Private_::ModuleInit_ *************************
110 ********************************************************************************
111 */
112namespace {
113 struct PrivateModuleData_ {
114 recursive_mutex fModuleMutex; // see GetEmitCritSection_
115 Emitter fEmitter;
116
117#if qStroika_Foundation_Debug_TraceToFile
118 ofstream fTraceFile;
119#endif
120
121#if qStroika_Foundation_Debug_TraceToFile
122 PrivateModuleData_ ()
123 {
124 fTraceFile.open (GetTraceFileName ().native ().c_str (), ios::out | ios::binary);
125 }
126#endif
127 };
128 PrivateModuleData_* sModuleData_{nullptr};
129}
130
131Debug::Private_::ModuleInit_::ModuleInit_ () noexcept
132{
133 Assert (sModuleData_ == nullptr);
134 sModuleData_ = new PrivateModuleData_ ();
135}
136Debug::Private_::ModuleInit_::~ModuleInit_ ()
137{
138 Assert (sModuleData_ != nullptr);
139 delete sModuleData_;
140#if qStroika_Foundation_Debug_AssertionsChecked
141 sModuleData_ = nullptr;
142#endif
143}
144
145/*
146 ********************************************************************************
147 ************************** Private_::Emitter ***********************************
148 ********************************************************************************
149 */
150auto Debug::Private_::Emitter::Get () noexcept -> Emitter&
151{
152 auto emitFirstTime = [] () {
153 // Cannot call DbgTrace or TraceContextBumper in this code (else hang cuz calls back to Emitter::Get ())
154 // which is why this function takes Emitter as argument!
155 sModuleData_->fEmitter.EmitTraceMessage ("***Starting TraceLog***"_f);
156 sModuleData_->fEmitter.EmitTraceMessage ("Starting at {}"_f, Time::DateTime::Now ().Format ());
157#if qStroika_Foundation_Debug_TraceToFile
158 sModuleData_->fEmitter.EmitTraceMessage ("TraceFileName: {}"_f, GetTraceFileName ());
159#endif
160 sModuleData_->fEmitter.EmitTraceMessage ("EXEPath={}"_f, Execution::GetEXEPath ());
161 sModuleData_->fEmitter.EmitTraceMessage ("<debug-state>"_f);
162 sModuleData_->fEmitter.EmitTraceMessage (" Debug::kBuiltWithAddressSanitizer = {}"_f, Debug::kBuiltWithAddressSanitizer);
163 sModuleData_->fEmitter.EmitTraceMessage (" Debug::kBuiltWithThreadSanitizer = {}"_f, Debug::kBuiltWithThreadSanitizer);
164 sModuleData_->fEmitter.EmitTraceMessage (" Debug::kBuiltWithUndefinedBehaviorSanitizer = {}"_f, Debug::kBuiltWithUndefinedBehaviorSanitizer);
165 sModuleData_->fEmitter.EmitTraceMessage (" Debug::IsRunningUnderValgrind () = {}"_f, Debug::IsRunningUnderValgrind ());
166 sModuleData_->fEmitter.EmitTraceMessage ("</debug-state>"_f);
167 };
168 static once_flag sOnceFlag_;
169 call_once (sOnceFlag_, [=] () { emitFirstTime (); });
170 return sModuleData_->fEmitter;
171}
172
173#if qStroika_Foundation_Debug_TraceToFile
174namespace {
175 void Emit2File_ (const char* text) noexcept
176 {
177 RequireNotNull (text);
178 AssertNotNull (sModuleData_);
179 try {
180 if (sModuleData_->fTraceFile.is_open ()) {
181 sModuleData_->fTraceFile << text;
182 sModuleData_->fTraceFile.flush ();
183 }
184 }
185 catch (...) {
187 }
188 }
189 void Emit2File_ (const wchar_t* text) noexcept
190 {
191 RequireNotNull (text);
192 try {
193 Emit2File_ (String{text}.AsNarrowSDKString (eIgnoreErrors).c_str ());
194 }
195 catch (...) {
197 }
198 }
199}
200#endif
201
202/*
203@DESCRIPTION: <p>This function takes a 'format' argument and then any number of additional arguments - exactly
204 like std::printf (). It calls std::vsprintf () internally. This can be called directly - regardless of the
205 @'qStroika_Foundation_Debug_DefaultTracingOn' flag - but is typically just called indirectly by calling
206 @'DbgTrace'.</p>
207*/
208void Debug::Private_::Emitter::EmitTraceMessage (const char* format, ...) noexcept
209{
210 if (TraceContextSuppressor::GetSuppressTraceInThisThread ()) {
211 return;
212 }
214 try {
215 va_list argsList;
216 va_start (argsList, format);
217 string tmp = Characters::CString::FormatV (format, argsList);
218 va_end (argsList);
219 SquishBadCharacters_ (&tmp);
220 AssureHasLineTermination (&tmp);
221 DoEmitMessage_ (0, Containers::Start (tmp), Containers::End (tmp));
222 }
223 catch (...) {
224 WeakAssert (false); // Should NEVER happen anymore becuase of new vsnprintf() stuff
225 // Most likely indicates invalid format string for varargs parameters
226 DoEmit_ (L"EmitTraceMessage FAILED internally (buffer overflow?)");
227 }
228}
229
230void Debug::Private_::Emitter::EmitTraceMessage (const wchar_t* format, ...) noexcept
231{
232 if (TraceContextSuppressor::GetSuppressTraceInThisThread ()) {
233 return;
234 }
236 try {
237 va_list argsList;
238 va_start (argsList, format);
239 wstring tmp = Characters::CString::FormatV (format, argsList);
240 va_end (argsList);
241 SquishBadCharacters_ (&tmp);
242 AssureHasLineTermination (&tmp);
243 DoEmitMessage_ (0, Containers::Start (tmp), Containers::End (tmp));
244 }
245 catch (...) {
246 WeakAssert (false); // Should NEVER happen anymore becuase of new vsnprintf() stuff
247 // Most likely indicates invalid format string for varargs parameters
248 DoEmit_ (L"EmitTraceMessage FAILED internally (buffer overflow?)");
249 }
250}
251
252auto Debug::Private_::Emitter::EmitTraceMessage_ (size_t bufferLastNChars, wstring_view format, Common::StdCompat::wformat_args&& args) noexcept
253 -> TraceLastBufferedWriteTokenType
254{
255 if (TraceContextSuppressor::GetSuppressTraceInThisThread ()) {
256 return 0;
257 }
259 try {
260 wstring tmp = Common::StdCompat::vformat (qStroika_Foundation_Characters_FMT_PREFIX_::wstring_view{format}, args);
261 SquishBadCharacters_ (&tmp);
262 AssureHasLineTermination (&tmp);
263 return DoEmitMessage_ (bufferLastNChars, Containers::Start (tmp), Containers::End (tmp));
264 }
265 catch (...) {
266 WeakAssert (false); // Should NEVER happen anymore becuase of new vsnprintf() stuff
267 // Most likely indicates invalid format string for varargs parameters
268 DoEmit_ (L"EmitTraceMessage FAILED internally (buffer overflow?)");
269 return 0;
270 }
271}
272
273void Debug::Private_::Emitter::EmitTraceMessage_ (wstring_view format, Common::StdCompat::wformat_args&& args) noexcept
274{
275 try {
276 EmitTraceMessage_ (vformat (qStroika_Foundation_Characters_FMT_PREFIX_::wstring_view{format}, args));
277 }
278 catch (...) {
279 }
280}
281void Debug::Private_::Emitter::EmitTraceMessage_ (string_view format, Common::StdCompat::format_args&& args) noexcept
282{
283 try {
284 Debug::Private_::Emitter::EmitTraceMessage_ (
285 Characters::String::FromNarrowSDKString (vformat (qStroika_Foundation_Characters_FMT_PREFIX_::string_view{format}, args)).As<wstring> ());
286 }
287 catch (...) {
288 }
289}
290
291void Debug::Private_::Emitter::EmitTraceMessage_ (const wstring& raw) noexcept
292{
293 if (TraceContextSuppressor::GetSuppressTraceInThisThread ()) {
294 return;
295 }
297 try {
298 wstring tmp = raw;
299 SquishBadCharacters_ (&tmp);
300 AssureHasLineTermination (&tmp);
301 DoEmitMessage_ (0, Containers::Start (tmp), Containers::End (tmp));
302 }
303 catch (...) {
304 WeakAssert (false); // Should NEVER happen anymore becuase of new vsnprintf() stuff
305 // Most likely indicates invalid format string for varargs parameters
306 DoEmit_ (L"EmitTraceMessage FAILED internally (buffer overflow?)");
307 }
308}
309
310namespace {
311 // .first is true iff added, and false if already present
312 // .second is the threadid to display
313 pair<bool, string> mkThreadLabelForThreadID_ (const Thread::IDType& threadID)
314 {
316 static atomic<int> sMinWidth_ = 4; // for MAIN
317 bool wasNew = false;
318 unsigned int threadIndex2Show = Thread::IndexRegistrar::sThe.GetIndex (threadID, &wasNew);
319 if (wasNew) {
320 if (threadIndex2Show >= 10000) {
321 sMinWidth_.store (5); // could enhance if we anticipate more threads
322 }
323 }
324 if (threadID == sMainThread_) {
325 static const string kMAIN_{"MAIN"sv};
326 return make_pair (wasNew, kMAIN_);
327 }
328 else {
329 char buf[1024];
330 (void)::snprintf (buf, std::size (buf), "%.*d", sMinWidth_.load (), threadIndex2Show);
331 return make_pair (wasNew, buf);
332 }
333 }
334 else {
335 // If this is deemed useful, then re-instate the mapping of threadID == sMainThread_ to "MAIN" with appropriate -- around it
336 return make_pair (false, Thread::FormatThreadID_A (threadID));
337 }
338 }
339}
340template <typename CHARTYPE>
341auto Debug::Private_::Emitter::DoEmitMessage_ (size_t bufferLastNChars, const CHARTYPE* s, const CHARTYPE* e) -> TraceLastBufferedWriteTokenType
342{
343 [[maybe_unused]] lock_guard critSec{sModuleData_->fModuleMutex};
344 FlushBufferedCharacters_ ();
345
346 auto curRelativeTime = Time::DisplayedRealtimeClock::now (); // same as Time::clock_cast<Time::DisplayedRealtimeClock> (Time::GetTickCount ())
347
348 {
349 char buf[1024];
350 Thread::IDType threadID = Execution::Thread::GetCurrentThreadID ();
351 pair<bool, string> threadIDInfo = mkThreadLabelForThreadID_ (threadID);
352 Verify (::snprintf (buf, std::size (buf), "[%s][%08.3f]\t", threadIDInfo.second.c_str (),
353 static_cast<double> (curRelativeTime.time_since_epoch ().count ())) > 0);
354 if (threadIDInfo.first) {
355 char buf2[1024]; // intentionally un-initialized
356 Verify (snprintf (buf2, std::size (buf2), "(NEW THREAD, index=%s Real Thread ID=%s)\t", threadIDInfo.second.c_str (),
357 Thread::FormatThreadID_A (threadID).c_str ()) > 0);
358#if __STDC_WANT_SECURE_LIB__
359 (void)::strcat_s (buf, buf2);
360#else
361 (void)::strcat (buf, buf2);
362#endif
363#if qStroika_Platform_POSIX
364 Verify (::snprintf (buf2, std::size (buf2), "(pthread_self=0x%lx)\t", (unsigned long)pthread_self ()) > 0);
365#if __STDC_WANT_SECURE_LIB__
366 (void)::strcat_s (buf, buf2);
367#else
368 (void)::strcat (buf, buf2);
369#endif
370#endif
371 }
372 Assert (::strlen (buf) < std::size (buf) / 2); // really just needs to be <, but since this buffer unchecked, break if we get CLOSE
373 DoEmit_ (buf);
374 }
375#if qStroika_Foundation_Debug_DefaultTracingOn
376 unsigned int contextDepth = TraceContextBumper::GetCount ();
377 for (unsigned int i = 0; i < contextDepth; ++i) {
378 DoEmit_ (L"\t");
379 }
380#endif
381 if (bufferLastNChars == 0) {
382 DoEmit_ (s, e);
383 ++fLastNCharBuf_Token_; // even if not buffering, increment, so other buffers known to be invalid
384 }
385 else {
386 Assert ((e - s) > static_cast<ptrdiff_t> (bufferLastNChars));
387 BufferNChars_ (bufferLastNChars, e - bufferLastNChars);
388 DoEmit_ (s, e - bufferLastNChars);
389 fLastNCharBuf_WriteTickcount_ = curRelativeTime;
390 ++fLastNCharBuf_Token_; // even if not buffering, increment, so other buffers known to be invalid
391 }
392 return fLastNCharBuf_Token_;
393}
394
395void Debug::Private_::Emitter::BufferNChars_ (size_t bufferLastNChars, const char* p)
396{
397 Assert (bufferLastNChars < std::size (fLastNCharBuf_CHAR_));
398 fLastNCharBufCharCount_ = bufferLastNChars;
399 (void)::memcpy (fLastNCharBuf_CHAR_, p, bufferLastNChars); // no need to nul-terminate because fLastNCharBufCharCount_ stores length
400 fLastNCharBuf_WCHARFlag_ = false;
401}
402
403void Debug::Private_::Emitter::BufferNChars_ (size_t bufferLastNChars, const wchar_t* p)
404{
405 Assert (bufferLastNChars < std::size (fLastNCharBuf_WCHAR_));
406 fLastNCharBufCharCount_ = bufferLastNChars;
407 (void)::memcpy (fLastNCharBuf_WCHAR_, p, bufferLastNChars * sizeof (wchar_t)); // no need to nul-terminate because fLastNCharBufCharCount_ stores length
408 fLastNCharBuf_WCHARFlag_ = true;
409}
410
411void Debug::Private_::Emitter::FlushBufferedCharacters_ ()
412{
413 if (fLastNCharBufCharCount_ != 0) {
414 if (fLastNCharBuf_WCHARFlag_) {
415 DoEmit_ (fLastNCharBuf_WCHAR_, fLastNCharBuf_WCHAR_ + fLastNCharBufCharCount_);
416 }
417 else {
418 DoEmit_ (fLastNCharBuf_CHAR_, fLastNCharBuf_CHAR_ + fLastNCharBufCharCount_);
419 }
420 fLastNCharBufCharCount_ = 0;
421 }
422}
423
424bool Debug::Private_::Emitter::UnputBufferedCharactersForMatchingToken (TraceLastBufferedWriteTokenType token)
425{
426 RequireNotNull (sModuleData_);
427 [[maybe_unused]] lock_guard critSec{sModuleData_->fModuleMutex};
428 // If the fLastNCharBuf_Token_ matches (no new tokens written since the saved one) and the time
429 // hasn't been too long (we currently write 1/100th second timestamp resolution).
430 // then blank unput (ignore) buffered characters, and return true so caller knows to write
431 // funky replacement for those characters.
432 if (fLastNCharBuf_Token_ == token and (Time::DisplayedRealtimeClock::now () - fLastNCharBuf_WriteTickcount_ < 20ms)) {
433 fLastNCharBufCharCount_ = 0;
434 return true;
435 }
436 return false; // assume old behavior for now
437}
438
439void Debug::Private_::Emitter::DoEmit_ (const char* p) noexcept
440{
441#if qStroika_Platform_Windows
442 constexpr size_t kMaxLen_ = 1023; // no docs on limit, but various hints the limit is somewhere between 1k and 4k. Empirically - just chops off after a point...
443 if (::strlen (p) < kMaxLen_) {
444 ::OutputDebugStringA (p);
445 }
446 else {
447 char buf[1024]; // @todo if/when we always support constexpr can use that here!
448 (void)::memcpy (buf, p, sizeof (buf));
449 buf[std::size (buf) - 1] = 0;
450 ::OutputDebugStringA (buf);
451 ::OutputDebugStringA ("...");
452 ::OutputDebugStringA (kEOL<char>);
453 }
454#endif
455#if qStroika_Foundation_Debug_TraceToFile
456 Emit2File_ (p);
457#endif
458}
459
460void Debug::Private_::Emitter::DoEmit_ (const wchar_t* p) noexcept
461{
462#if qStroika_Platform_Windows
463 constexpr size_t kMaxLen_ = 1023; // no docs on limit, but various hints the limit is somewhere between 1k and 4k. Empirically - just chops off after a point...
464 if (::wcslen (p) < kMaxLen_) {
465 ::OutputDebugStringW (p);
466 }
467 else {
468 wchar_t buf[1024]; // @todo if/when we always support constexpr can use that here!
469 (void)::memcpy (buf, p, sizeof (buf));
470 buf[std::size (buf) - 1] = 0;
471 ::OutputDebugStringW (buf);
472 ::OutputDebugStringW (L"...");
473 ::OutputDebugStringW (kEOL<wchar_t>);
474 }
475#endif
476#if qStroika_Foundation_Debug_TraceToFile
477 Emit2File_ (p);
478#endif
479}
480
481void Debug::Private_::Emitter::DoEmit_ (const char* p, const char* e) noexcept
482{
483 try {
484 size_t len = e - p;
485 StackBuffer<char> buf{Memory::eUninitialized, len + 1};
486 (void)::memcpy (buf.begin (), p, len);
487 buf.begin ()[len] = '\0';
488 DoEmit_ (buf.begin ());
489 }
490 catch (...) {
492 }
493}
494
495/*
496 [Succeeded] (1 seconds) [42] Foundation::Execution::Other (scp ../Builds/raspberrypi-g++-12-release-sanitize_address/Tests/Test42...; ssh lewis@192.168.244.20 /tmp/Test42)
497=================================================================
498==24967==ERROR: AddressSanitizer: stack-use-after-scope on address 0xbefb9b80 at pc 0x0048c10f bp 0xbefb9688 sp 0xbefb9694
499WRITE of size 100 at 0xbefb9b80 thread T0
500 #0 0x48c10c in __interceptor_memcpy (/tmp/Test43+0x6c10c)
501 #1 0x6189ee in memcpy /usr/arm-linux-gnueabihf/include/bits/string_fortified.h:29
502 #2 0x6189ee in Stroika::Foundation::Debug::Private_::Emitter::DoEmit_(wchar_t const*, wchar_t const*) /home/lewis/Sandbox/Stroika-Build-Dir-Ubuntu2204-Cross-Compile2RaspberryPi/Library/Sources/Stroika/Foundation/Debug/Trace.cpp:553
503 #3 0x6236c8 in int Stroika::Foundation::Debug::Private_::Emitter::DoEmitMessage_<wchar_t>(unsigned int, wchar_t const*, wchar_t const*) /home/lewis/Sandbox/Stroika-Build-Dir-Ubuntu2204-Cross-Compile2RaspberryPi/Library/Sources/Stroika/Foundation/Debug/Trace.cpp:432
504 #4 0x61928e in Stroika::Foundation::Debug::Private_::Emitter::EmitTraceMessage(wchar_t const*, ...) /home/lewis/Sandbox/Stroika-Build-Dir-Ubuntu2204-Cross-Compile2RaspberryPi/Library/Sources/Stroika/Foundation/Debug/Trace.cpp:299
505 #5 0x6198ba in Stroika::Foundation::Debug::TraceContextBumper::~TraceContextBumper() /home/lewis/Sandbox/Stroika-Build-Dir-Ubuntu2204-Cross-Compile2RaspberryPi/Library/Sources/Stroika/Foundation/Debug/Trace.cpp:645
506 #6 0x6198ba in Stroika::Foundation::Debug::TraceContextBumper::~TraceContextBumper() /home/lewis/Sandbox/Stroika-Build-Dir-Ubuntu2204-Cross-Compile2RaspberryPi/Library/Sources/Stroika/Foundation/Debug/Trace.cpp:634
507 #7 0x5423cc in DoTests_ /home/lewis/Sandbox/Stroika-Build-Dir-Ubuntu2204-Cross-Compile2RaspberryPi/Tests/43/Test.cpp:376
508 #8 0x54cb52 in DoRegressionTests_ /home/lewis/Sandbox/Stroika-Build-Dir-Ubuntu2204-Cross-Compile2RaspberryPi/Tests/43/Test.cpp:568
509 #9 0x56ac3c in Stroika::TestHarness::PrintPassOrFail(void (*)()) ../TestHarness/TestHarness.cpp:89
510 #10 0xb6d1a3bc in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
511 #11 0xb6d1a4c4 in __libc_start_main_impl csu/libc-start.c:360
512
513Address 0xbefb9b80 is located in stack of thread T0 at offset 128 in frame
514 #0 0x6188e8 in Stroika::Foundation::Debug::Private_::Emitter::DoEmit_(wchar_t const*, wchar_t const*) /home/lewis/Sandbox/Stroika-Build-Dir-Ubuntu2204-Cross-Compile2RaspberryPi/Library/Sources/Stroika/Foundation/Debug/Trace.cpp:549
515
516 This frame has 1 object(s):
517 [48, 4152) 'buf' (line 552) <== Memory access at offset 128 is inside this variable
518HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork
519*/
520#if qCompilerAndStdLib_arm_asan_FaultStackUseAfterScope_Buggy
521Stroika_Foundation_Debug_ATTRIBUTE_NO_SANITIZE_ADDRESS
522#endif
523 void Debug::Private_::Emitter::DoEmit_ (const wchar_t* p, const wchar_t* e) noexcept
524{
525 try {
526 size_t len = e - p;
527 StackBuffer<wchar_t> buf{Memory::eUninitialized, len + 1};
528 (void)::memcpy (buf.begin (), p, len * sizeof (wchar_t));
529 buf.begin ()[len] = '\0';
530 DoEmit_ (buf.begin ());
531 }
532 catch (...) {
534 }
535}
536
537/*
538 ********************************************************************************
539 ************************** Debug::GetDbgTraceThreadName ************************
540 ********************************************************************************
541 */
542wstring Debug::GetDbgTraceThreadName (thread::id threadID)
543{
544 return String::FromNarrowSDKString (GetDbgTraceThreadName_A (threadID)).As<wstring> ();
545}
546string Debug::GetDbgTraceThreadName_A (thread::id threadID)
547{
548 return mkThreadLabelForThreadID_ (threadID).second;
549}
550
551#if qStroika_Foundation_Debug_TraceToFile
552/*
553 ********************************************************************************
554 ************************* Debug::GetTraceFileName ******************************
555 ********************************************************************************
556 */
557filesystem::path Debug::GetTraceFileName ()
558{
559 auto mkTraceFileName_ = [] () -> filesystem::path {
560 // Use TempDir instead of EXEDir because on vista, installation permissions prevent us from (easily) writing in EXEDir.
561 // (could fix of course, but I'm not sure desirable - reasonable defaults)
562 //
563 // Don't want to use TempFileLibrarian cuz we don't want these deleted on app exit
564 SDKString mfname;
565 {
566 try {
567 mfname = Execution::GetEXEPath ().native ();
568 }
569 catch (...) {
570 mfname = SDKSTR ("{unknown}");
571 }
572 {
573 size_t i = mfname.rfind (filesystem::path::preferred_separator);
574 if (i != SDKString::npos) {
575 mfname = mfname.substr (i + 1);
576 }
577 i = mfname.rfind ('.');
578 if (i != SDKString::npos) {
579 mfname.erase (i);
580 }
581 }
582 for (auto i = mfname.begin (); i != mfname.end (); ++i) {
583 if (*i == ' ') {
584 *i = '-';
585 }
586 }
587 }
588 SDKString nowstr = Time::DateTime::Now ().Format (Time::DateTime::kISO8601Format).AsSDKString (); // use eISO8601 instead of eCurrentLocale cuz locale CTOR not safe to construct before main
589 for (auto i = nowstr.begin (); i != nowstr.end (); ++i) {
590 if (*i == ':') {
591 *i = '-';
592 }
593 if (*i == '/' or *i == ' ') {
594 *i = '_';
595 }
596 }
598 CString::Format (SDKSTR ("TraceLog_%s_PID#%d-%s.txt"), mfname.c_str (), (int)Execution::GetCurrentProcessID (), nowstr.c_str ());
599 };
600 static filesystem::path sTraceFileName_ = mkTraceFileName_ ();
601 return sTraceFileName_;
602}
603#endif
604
605/*
606 ********************************************************************************
607 ****************************** TraceContextBumper ******************************
608 ********************************************************************************
609 */
610#if qStroika_Foundation_Debug_DefaultTracingOn
611TraceContextBumper::TraceContextBumper (CHAR_ARRAY_T mainName, CHAR_ARRAY_T extraTextAtTop) noexcept
612 : fDoEndMarker{true}
613{
614 Require (char_traits<wchar_t>::length (mainName.data ()) <= kMaxContextNameLen_); // assert NUL-terminated
615 if (extraTextAtTop.empty () or extraTextAtTop[0] == '\0') {
616 auto mainNameData = mainName.data ();
617 fLastWriteToken_ = Private_::Emitter::Get ().EmitTraceMessage_ (3 + ::wcslen (kEOL<wchar_t>), L"<{}> {{"sv,
618 Common::StdCompat::make_wformat_args (mainNameData));
619 }
620 else {
621 auto mainNameData = mainName.data ();
622 auto extraTextAtTopData = extraTextAtTop.data ();
623 fLastWriteToken_ = Emitter::Get ().EmitTraceMessage_ (3 + ::wcslen (kEOL<wchar_t>), L"<{} ({})> {{"sv,
624 Common::StdCompat::make_wformat_args (mainNameData, extraTextAtTopData));
625 }
626 size_t len = char_traits<wchar_t>::length (mainName.data ());
627 char_traits<wchar_t>::copy (fSavedContextName_.data (), mainName.data (), len);
628 if (len >= kMaxContextNameLen_ - 1) {
629 char_traits<wchar_t>::copy (&fSavedContextName_.data ()[len - 3], L"...", 3);
630 }
631 fSavedContextName_[len] = '\0';
632 *(std::end (fSavedContextName_) - 1) = '\0';
633 IncCount_ ();
634}
635
636TraceContextBumper::TraceContextBumper (const wchar_t* contextName, const wchar_t* extraFmt, ...) noexcept
637 : fDoEndMarker{true}
638{
639 // ********************** DEPRECATED API *********************
640 try {
641 va_list argsList;
642 va_start (argsList, extraFmt);
643 wstring tmpFmtV = Characters::CString::FormatV (extraFmt, argsList);
644 fLastWriteToken_ = Emitter::Get ().EmitTraceMessage_ (3 + ::wcslen (kEOL<wchar_t>), L"<{} ({})> {{"sv,
645 Common::StdCompat::make_wformat_args (contextName, tmpFmtV));
646 va_end (argsList);
647 size_t len = min (kMaxContextNameLen_ - 1, char_traits<wchar_t>::length (contextName));
648 char_traits<wchar_t>::copy (fSavedContextName_.data (), contextName, len);
649 if (len >= kMaxContextNameLen_ - 1) {
650 char_traits<wchar_t>::copy (&fSavedContextName_.data ()[len - 3], L"...", 3);
651 }
652 *(std::end (fSavedContextName_) - 1) = '\0';
653 fSavedContextName_[len] = '\0';
654 IncCount_ ();
655 }
656 catch (...) {
657 }
658}
659
660unsigned int TraceContextBumper::GetCount ()
661{
662 return tTraceContextDepth_;
663}
664
665void TraceContextBumper::IncCount_ () noexcept
666{
667 ++tTraceContextDepth_;
668}
669
670void TraceContextBumper::DecrCount_ () noexcept
671{
672 --tTraceContextDepth_;
673}
674
675TraceContextBumper::~TraceContextBumper () noexcept
676{
677 DecrCount_ ();
678 if (fDoEndMarker) {
679 RequireNotNull (sModuleData_);
680 try {
681 [[maybe_unused]] lock_guard critSec{sModuleData_->fModuleMutex};
682 if (Emitter::Get ().UnputBufferedCharactersForMatchingToken (fLastWriteToken_)) {
683 Emitter::Get ().EmitUnadornedText ("/>");
684 Emitter::Get ().EmitUnadornedText (kEOL<char>);
685 }
686 else {
687 Emitter::Get ().EmitTraceMessage ("}} </{}>"_f, fSavedContextName_.data ());
688 }
689 }
690 catch (...) {
691 // not much of a chance of successfully reporting a problem here, but DTOR must be noexcept
692 }
693 }
694}
695#endif
#define AssertNotNull(p)
Definition Assertions.h:336
#define RequireNotNull(p)
Definition Assertions.h:350
#define WeakAssert(c)
A WeakAssert() is for things that aren't guaranteed to be true, but are overwhelmingly likely to be t...
Definition Assertions.h:441
#define AssertNotReached()
Definition Assertions.h:358
#define Verify(c)
Definition Assertions.h:422
#define CompileTimeFlagChecker_SOURCE(NS_PREFIX, NAME, VALUE)
#define qStroika_Foundation_Debug_ShowThreadIndex
if true, emit a much shorter thread ID, making - I suspect (testing) for terser and clearer tracelogs...
Definition Trace.h:87
#define qStroika_Foundation_Debug_TraceToFile
Definition Trace.h:49
Support for running under valgrind memcheck - the only valgrind tool Stroika supports (see Documentat...
String is like std::u32string, except it is much easier to use, often much more space efficient,...
Definition String.h:201
nonvirtual string AsNarrowSDKString() const
Definition String.inl:832
static String FromNarrowSDKString(const char *from)
Definition String.inl:472
Logically halfway between std::array and std::vector; Smart 'direct memory array' - which when needed...
basic_string< SDKChar > SDKString
Definition SDKString.h:38
CONTAINER::value_type * End(CONTAINER &c)
For a contiguous container (such as a vector or basic_string) - find the pointer to the end of the co...
CONTAINER::value_type * Start(CONTAINER &c)
For a contiguous container (such as a vector or basic_string) - find the pointer to the start of the ...