Repository navigation
Expand file tree
/
Copy pathlog_validation.cpp
More file actions
865 lines (787 loc) · 36.5 KB
/
Copy pathlog_validation.cpp
File metadata and controls
865 lines (787 loc) · 36.5 KB
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
/*
* Copyright 2026 CEA (www.cea.fr)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ============================================================================
// The library's log (fast_allocators/internal/log_core.h), alone: no array,
// no variant.
// ============================================================================
//
// 1. the environment: CHUNK_LOG, a legacy switch and CHUNK_LOG_FILE, set
// before the first message, are read at it -- the levels apply, the
// switch raises its channel and is warned about, the file receives the
// lines, and an item not understood is reported there;
// 2. parse_spec: bare levels, channel=level, left to right, spaces, empty
// items, the items not understood;
// 3. filtering through configure(): what gets through per channel and
// level, and the arguments of a message filtered out are not evaluated;
// 4. a sink: the records it receives (level, channel, text, line), a sink
// that logs itself, back to the default sink;
// 5. CHUNK_LOG_FIRST_N and CHUNK_LOG_POW2 count right;
// 6. a message longer than line_max is cut, with "...";
// 7. no allocation on the path of a message (operator new is counted;
// under TSan, through the sanitizer's malloc hook); a std::complex and a
// type with no formatter spelled there too, "(re+imi)" and its bytes in
// hex -- outside the fatal children, where the coverage counts them;
// 8. 8 threads writing to the default sink at once: every line in the file
// whole, none lost;
// 9. the fatal level, each case in a child (this executable re-run with
// --fatal K): CHUNK_INVARIANT_FAILED writes its block and the backtrace
// on stderr, the record reaches CHUNK_LOG_FILE or the program's sink,
// element values of any type are spelled; 8 threads failing at once
// give one report; a failure inside the sink still stops;
// CHUNK_CHECK_FAILED stops a check build and logs an error elsewhere;
// and fast_allocators' FAST_ALLOC_FATAL gives the same report;
// CHUNK_BREAK_ON_FAILURE=1 stops the child on SIGTRAP, after the report;
// 10. the debugger detection of the fatal level (fatal.h's tracer_pid,
// is_debugger_name) on fixed texts of /proc/<pid>/status and comm.
//
// With --debugger <gdb> [<strace>] (the test log_break_on_failure), instead:
// the fatal child of check 9 run under gdb stops on SIGTRAP in the fatal
// path, the report written, and continued, aborts; with
// CHUNK_BREAK_ON_FAILURE=0 it only aborts; under strace (which traces the
// process too, but is no debugger) it aborts, with no SIGTRAP. Exit status 77
// (skipped) when gdb cannot be run.
//
// Exit status 0 when every check passes.
#include <algorithm> // std::ranges::find
#include <array> // std::array
#include <atomic> // std::atomic
#include <complex> // std::complex (checks 7 and 9)
#include <cstdint> // std::uint32_t (checks 7 and 9)
#include <cstdio> // std::remove, std::sscanf, std::perror
#include <csignal> // SIGTRAP, SIGABRT (check 9, --debugger)
#include <cstdlib> // std::malloc, std::free, std::abort, std::atexit
#include <cstring> // std::memcpy
#include <filesystem> // std::filesystem::temp_directory_path, remove_all (private_temp_dir)
#include <format> // std::format (the expected address, check 7)
#include <fstream> // std::ifstream
#include <new> // std::bad_alloc
#include <string> // std::string, std::getline
#include <string_view> // std::string_view
#include <system_error> // std::error_code (private_temp_dir's cleanup)
#include <thread> // std::thread
#include <vector> // std::vector
#include <stdlib.h> // setenv, unsetenv, mkdtemp (POSIX: <cstdlib> need not declare them)
#include <sys/wait.h> // WIFEXITED, WEXITSTATUS
#include <unistd.h> // getpid (the expected expansion of CHUNK_LOG_FILE's %p)
#include "chunk/log.h" // shrink_array::logging, CHUNK_LOG
#include "chunk/internal/invariant_check.h" // CHUNK_INVARIANT_FAILED, CHUNK_CHECK_FAILED
#include "chunk/print.h" // shrink_array::println
using shrink_array::println;
namespace logging = shrink_array::logging;
using logging::Channel;
using logging::Level;
// --- Allocation counter (check 7) -------------------------------------------
// TSan's runtime brings its own operator new / operator delete (clang links
// libclang_rt.tsan_cxx.a --whole-archive): replacing them there is a duplicate
// symbol at link time. Under TSan the counter is the sanitizer's malloc hook,
// called for every user allocation, operator new included; elsewhere, the
// replaceable global operator new below. The choice is the file-scope
// definition of operator new itself, hence the preprocessor.
#if defined(__SANITIZE_THREAD__)
#define LOG_VALIDATION_TSAN 1
#elif defined(__has_feature)
#if __has_feature(thread_sanitizer)
#define LOG_VALIDATION_TSAN 1
#endif
#endif
namespace
{
std::atomic<long> g_news{0};
thread_local bool g_counting = false;
void count_allocation() noexcept
{
if (g_counting)
{
g_news.fetch_add(1, std::memory_order_relaxed);
}
}
} // namespace
#ifdef LOG_VALIDATION_TSAN
// Declared here rather than through <sanitizer/allocator_interface.h>, which
// not every toolchain installs (the symbol is in the runtime of both clang and
// GCC).
extern "C" int __sanitizer_install_malloc_and_free_hooks(void (*malloc_hook)(const volatile void*, std::size_t),
void (*free_hook)(const volatile void*));
namespace
{
void on_malloc(const volatile void* /*p*/, std::size_t /*n*/)
{
count_allocation();
}
void on_free(const volatile void* /*p*/) {}
// Installed before main; a failure leaves the counter at 0, which check 7's
// first check ("the counter counts") reports.
[[maybe_unused]] const int g_hooks_installed = __sanitizer_install_malloc_and_free_hooks(on_malloc, on_free);
} // namespace
#else
void* operator new(std::size_t size)
{
count_allocation();
if (void* ptr = std::malloc(size == 0 ? 1 : size))
{
return ptr;
}
throw std::bad_alloc{};
}
void operator delete(void* ptr) noexcept
{
std::free(ptr);
}
void operator delete(void* ptr, std::size_t /*n*/) noexcept
{
std::free(ptr);
}
#endif
namespace
{
int g_fails = 0;
void check(bool ok, std::string_view what)
{
if (!ok)
{
++g_fails;
println("FAIL {}", what);
}
}
// --- A capturing sink ---------------------------------------------------------
struct Captured
{
Level level;
Channel channel;
std::string message;
unsigned line;
};
std::vector<Captured> g_captured;
void capture(const logging::Record& record, void* /*user*/) noexcept
{
// A Sink is noexcept: an allocation failure stops the test with a message
// rather than escaping into std::terminate.
try
{
g_captured.emplace_back(record.level, record.channel, std::string{record.message}, record.location.line());
}
catch (...)
{
std::fputs("log_validation: capture: out of memory\n", stderr);
std::abort();
}
}
// Preallocated: what check 7's sink writes into, so the sink allocates nothing.
std::array<char, logging::line_max> g_last{};
std::size_t g_last_len = 0;
void capture_no_alloc(const logging::Record& record, void* /*user*/) noexcept
{
g_last_len = record.message.size();
std::memcpy(g_last.data(), record.message.data(), record.message.size());
}
void logging_sink(const logging::Record& record, void* /*user*/) noexcept
{
capture(record, nullptr);
CHUNK_LOG(warn, general, "from inside the sink"); // must reach the default sink, not deadlock
}
std::vector<std::string> read_lines(const std::string& path)
{
std::vector<std::string> lines;
std::ifstream in(path);
std::string line;
while (std::getline(in, line))
{
lines.push_back(line);
}
return lines;
}
std::string g_log_path; // CHUNK_LOG_FILE, expanded
// --- 1 ----------------------------------------------------------------------
void check_environment()
{
using enum Channel;
check(logging::enabled(rechunk, Level::debug), "env: CHUNK_LOG rechunk=debug applies");
check(!logging::enabled(rechunk, Level::trace), "env: rechunk stops at debug");
check(logging::enabled(pool, Level::warn), "env: the bare level warn applies to pool");
check(!logging::enabled(pool, Level::info), "env: pool stops at warn");
check(logging::enabled(alloc, Level::trace), "env: FAST_ALLOC_TRACE=1 raises alloc to trace");
const auto& switches = logging::detail::legacy_switches;
const auto trace =
std::ranges::find(switches, std::string_view{"FAST_ALLOC_TRACE"}, &logging::detail::LegacySwitch::name);
check(trace != switches.end() && logging::detail::is_set(*trace), "env: FAST_ALLOC_TRACE=1 is set");
check(std::ranges::find(switches, std::string_view{"CHUNK_RECHUNK_CHURN"}, &logging::detail::LegacySwitch::name) ==
switches.end(),
"env: CHUNK_RECHUNK_CHURN is no longer a switch (CHUNK_LOG=rechunk=debug)");
check(logging::enabled(ledger, Level::info), "env: CHUNK_LEDGER_REPORT=1 raises ledger to info");
check(!logging::enabled(arena, Level::info), "env: arena stays at warn (CHUNK_ARENA_REPORT unset)");
CHUNK_LOG(warn, general, "first line through the default sink");
const auto lines = read_lines(g_log_path);
bool bad_item_reported = false;
bool first_line = false;
bool deprecated = false;
bool report_deprecated = false;
for (const auto& line : lines)
{
deprecated |=
line.starts_with("[shrink_array][env][W][") &&
line.ends_with("] FAST_ALLOC_TRACE is deprecated: it means CHUNK_LOG=alloc=trace, which it now sets");
report_deprecated |=
line.starts_with("[shrink_array][env][W][") &&
line.ends_with("] CHUNK_LEDGER_REPORT is deprecated: it means CHUNK_LOG=ledger=info, which it now sets");
bad_item_reported |=
line.starts_with("[shrink_array][env][W][") && line.find("\"verbose\"") != std::string::npos;
first_line |=
line.starts_with("[shrink_array][general][W][") && line.ends_with("] first line through the default sink");
}
check(bad_item_reported, "env: CHUNK_LOG item \"verbose\" reported in CHUNK_LOG_FILE");
check(first_line, "env: a message reaches CHUNK_LOG_FILE with its prefix");
check(deprecated, "env: a deprecated switch is warned about");
check(report_deprecated, "env: a former report switch is warned about");
}
// --- 2 ----------------------------------------------------------------------
void check_parse()
{
using logging::detail::default_max;
using logging::detail::parse_spec;
constexpr auto ix = [](Channel chan) { return static_cast<std::size_t>(chan); };
auto spec = parse_spec("", default_max);
check(spec.n_bad == 0 && spec.max == default_max, "parse: empty spec keeps the base");
check(default_max[ix(Channel::rechunk)] == Level::info && default_max[ix(Channel::memory)] == Level::warn &&
default_max[ix(Channel::general)] == Level::warn,
"default: rechunk at info (the applied re-chunks), every other channel at warn");
spec = parse_spec("debug", default_max);
check(spec.max[ix(Channel::env)] == Level::debug && spec.max[ix(Channel::advisor)] == Level::debug,
"parse: a bare level sets every channel");
spec = parse_spec("warn,rechunk=trace", default_max);
check(spec.max[ix(Channel::rechunk)] == Level::trace && spec.max[ix(Channel::pool)] == Level::warn,
"parse: channel=level after the bare level");
spec = parse_spec("rechunk=trace,error", default_max);
check(spec.max[ix(Channel::rechunk)] == Level::error, "parse: left to right, a later bare level wins");
spec = parse_spec(" info , pool = debug ,, ", default_max);
check(spec.n_bad == 0 && spec.max[ix(Channel::pool)] == Level::debug && spec.max[ix(Channel::drain)] == Level::info,
"parse: spaces and empty items");
spec = parse_spec("off", default_max);
check(spec.max[ix(Channel::general)] == Level::fatal, "parse: off lets nothing but fatal");
spec = parse_spec("loud,nochan=debug,pool=loud,fatal,pool=info,a,b,c", default_max);
check(spec.n_bad == 7 && spec.bad[0] == "loud" && spec.bad[1] == "nochan=debug" && spec.bad[2] == "pool=loud" &&
spec.bad[3] == "fatal",
"parse: the items not understood, in order (fatal is not a level CHUNK_LOG sets)");
check(spec.max[ix(Channel::pool)] == Level::info, "parse: a bad item changes nothing, the good ones apply");
}
// --- 3 ----------------------------------------------------------------------
void check_filter()
{
using enum Channel;
using enum Level;
logging::configure("warn,drain=info");
check(logging::enabled(drain, info), "filter: drain=info lets info");
check(!logging::enabled(drain, debug), "filter: drain=info stops debug");
check(logging::enabled(general, error), "filter: warn lets error");
check(!logging::enabled(general, info), "filter: warn stops info");
int evaluated = 0;
const auto touch = [&] { return ++evaluated; };
CHUNK_LOG(debug, general, "filtered out {}", touch());
check(evaluated == 0, "filter: the arguments of a message filtered out are not evaluated");
logging::configure("off");
CHUNK_LOG(error, general, "filtered out {}", touch());
check(evaluated == 0, "filter: off stops error");
logging::configure("warn");
}
// --- 4 ----------------------------------------------------------------------
void check_sink()
{
g_captured.clear();
logging::set_sink(capture);
logging::configure("warn,ompt=debug");
const unsigned line = __LINE__ + 1;
CHUNK_LOG(debug, ompt, "value {} and {}", 42, std::string_view{"text"});
CHUNK_LOG(debug, pool, "filtered out");
CHUNK_LOG(error, pool, "kept");
check(g_captured.size() == 2, "sink: two records of three");
if (g_captured.size() == 2)
{
check(g_captured[0].level == Level::debug && g_captured[0].channel == Channel::ompt,
"sink: level and channel of the record");
check(g_captured[0].message == "value 42 and text", "sink: the message, formatted, no prefix");
check(g_captured[0].line == line, "sink: the source location is the caller's");
check(g_captured[1].level == Level::error && g_captured[1].message == "kept", "sink: second record");
}
g_captured.clear();
logging::set_sink(logging_sink);
CHUNK_LOG(warn, general, "to a sink that logs");
check(g_captured.size() == 1, "sink: a sink that logs gets its record once (its own goes to the default)");
logging::set_sink(nullptr);
logging::configure("warn");
}
// --- 5 ----------------------------------------------------------------------
void check_rate_limits()
{
g_captured.clear();
logging::set_sink(capture);
for (int i = 0; i < 10; ++i)
{
CHUNK_LOG_FIRST_N(3, warn, general, "first-n {}", i);
}
check(g_captured.size() == 4, "FIRST_N(3) over 10: 3 messages and the suppression line");
if (g_captured.size() == 4)
{
check(g_captured[2].message == "first-n 2", "FIRST_N: the third message is the third call's");
check(g_captured[3].message.starts_with("(further messages from ") &&
g_captured[3].message.ends_with(" suppressed)"),
"FIRST_N: the suppression line");
}
g_captured.clear();
for (int i = 1; i <= 100; ++i)
{
CHUNK_LOG_POW2(warn, general, "pow2 {}", i);
}
check(g_captured.size() == 7, "POW2 over 100: calls 1, 2, 4, 8, 16, 32, 64");
if (g_captured.size() == 7)
{
check(g_captured[6].message == "pow2 64", "POW2: the 7th message is the 64th call's");
}
logging::set_sink(nullptr);
}
// --- 6 ----------------------------------------------------------------------
void check_truncation()
{
g_captured.clear();
logging::set_sink(capture);
const std::string big(3 * logging::line_max, 'x');
CHUNK_LOG(warn, general, "{}", big);
check(g_captured.size() == 1 && g_captured[0].message.size() == logging::line_max &&
g_captured[0].message.ends_with("xx..."),
"truncation: line_max bytes, ending in ...");
logging::set_sink(nullptr);
}
// --- 7 ----------------------------------------------------------------------
std::vector<int>* g_kept = nullptr; // stored: the counter's own check below cannot be elided
void check_no_allocation()
{
g_news.store(0);
g_counting = true;
g_kept = new std::vector<int>(100);
g_counting = false;
check(g_news.load() == 2, "no allocation: the counter counts (a vector and its buffer)");
delete g_kept;
logging::set_sink(capture_no_alloc);
const double value = 2.5;
g_news.store(0);
g_counting = true;
CHUNK_LOG(warn, general, "no allocation: {} {:.3f} {} {} {}", 123456789L, value, std::string_view{"view"}, &value,
value);
CHUNK_LOG(debug, general, "filtered out {}", 1);
CHUNK_LOG_POW2(warn, general, "pow2 no allocation {}", 1);
g_counting = false;
check(g_news.load() == 0, "no allocation on the path of a message");
check(std::string_view(g_last.data(), g_last_len) == "pow2 no allocation 1", "no allocation: the messages arrived");
logging::set_sink(nullptr);
// A pointer to an object is spelled as its address, with no cast at the
// call; a char pointer stays a string.
std::array<char, logging::line_max> buf{};
const int number = 3;
const char* const str = "text";
const std::size_t len = logging::detail::format_message(buf.data(), "{} {}", &number, str);
check(std::string_view(buf.data(), len) == std::format("{} text", static_cast<const void*>(&number)),
"a pointer is spelled as its address, a char pointer as a string");
// std::complex as "(re+imi)", a type with no formatter as its bytes in
// memory order (a union: its bytes on every branch), on this path too and
// still without allocation.
union Word
{
std::uint32_t u;
float f;
};
const Word word{0x01020304U};
g_news.store(0);
g_counting = true;
const std::size_t n2 = logging::detail::format_message(
buf.data(), "complex {} {} bytes {}", std::complex<double>(1.0, -2.0), std::complex<float>(0.5F, 3.0F), word);
g_counting = false;
check(std::string_view(buf.data(), n2) == "complex (1-2i) (0.5+3i) bytes 0x04030201",
"std::complex and a type with no formatter spelled on the message path");
check(g_news.load() == 0, "no allocation for a std::complex or a type with no formatter");
}
// --- 8 ----------------------------------------------------------------------
void check_threads()
{
constexpr int n_threads = 8;
constexpr int n_lines = 2000;
logging::configure("warn,general=info");
{
std::vector<std::thread> team;
for (int t = 0; t < n_threads; ++t)
{
team.emplace_back(
[t]
{
for (int i = 0; i < n_lines; ++i)
{
CHUNK_LOG(info, general, "thread {} line {} {}", t, i, std::string_view{"padding-padding"});
}
});
}
for (auto& th : team)
{
th.join();
}
}
std::array<int, n_threads> seen{};
int broken = 0;
for (const auto& line : read_lines(g_log_path))
{
if (!line.starts_with("[shrink_array][general][I]["))
{
continue;
}
int thread = -1;
int line_no = -1;
if (const auto pos = line.find("] thread ");
pos == std::string::npos ||
std::sscanf(line.c_str() + pos, "] thread %d line %d", &thread, &line_no) != 2 || thread < 0 ||
thread >= n_threads || !line.ends_with(" padding-padding"))
{
++broken;
continue;
}
++seen[static_cast<std::size_t>(thread)];
}
check(broken == 0, "threads: every line whole");
bool all = true;
for (const int lines_seen : seen)
{
all &= (lines_seen == n_lines);
}
check(all, "threads: every line of every thread in the file");
logging::configure("warn");
}
// --- 9 ----------------------------------------------------------------------
struct NoFormatter // an element type with no std::formatter: printed as its bytes
{
std::uint32_t a;
std::uint32_t b;
};
void fatal_sink(const logging::Record& record, void* /*user*/) noexcept
{
std::printf("SINK %s: %.*s\n", std::string(logging::name(record.level)).c_str(),
static_cast<int>(record.message.size()), record.message.data());
std::fflush(stdout);
}
void failing_sink(const logging::Record& record, void* /*user*/) noexcept
{
CHUNK_INVARIANT_FAILED("failure inside the sink, on \"{}\"", record.message);
}
/// @brief The child of check 9: case @p which, which aborts (or, case 4 in a
/// build that is not a check build, returns).
int run_fatal(int which)
{
switch (which)
{
case 0: // block, backtrace, bytes and complex spelled, record in CHUNK_LOG_FILE
CHUNK_INVARIANT_FAILED("value {} complex {} bytes {}", 7, std::complex<double>(1.0, -2.0),
NoFormatter{1, 2});
case 1: // 8 threads at once: one report
{
std::atomic<int> ready{0};
std::vector<std::thread> team;
for (int t = 0; t < 8; ++t)
{
team.emplace_back(
[&ready, t]
{
ready.fetch_add(1);
while (ready.load() < 8)
{
// spin until the 8 threads are in
}
CHUNK_INVARIANT_FAILED("thread {} failed", t);
});
}
for (auto& th : team)
{
th.join();
}
return 0;
}
case 2: // the record reaches the program's sink
logging::set_sink(fatal_sink);
CHUNK_INVARIANT_FAILED("to the sink {}", 42);
case 3: // a failure inside the sink still stops, without waiting on the sink's lock
logging::set_sink(failing_sink);
CHUNK_LOG(warn, general, "trigger");
return 0;
case 4: // CHUNK_CHECK_FAILED: stops a check build, logs elsewhere
CHUNK_CHECK_FAILED(drain, "check failed {}", 5);
std::printf("carried on\n");
return 0;
case 5: // fast_allocators' fatal level: the same report, headed [CRITICAL_FAILURE]
FAST_ALLOC_FATAL("allocator failure {}", 6);
default:
return 2;
}
}
/// @brief This process's own temporary directory, for the log files and the
/// children's output: made once by mkdtemp() under $TMPDIR (else /tmp),
/// readable by this user only, removed with its content at exit -- not
/// a fixed /tmp/<name>.<pid> that another user of the node could take
/// first. (The grouped harnesses have validation::temp_path(); this
/// program is built on its own.)
const std::string& private_temp_dir()
{
static const std::string dir = []
{
std::string templ = (std::filesystem::temp_directory_path() / "shrink_log_validation.XXXXXX").string();
if (::mkdtemp(templ.data()) == nullptr)
{
std::perror("log_validation: mkdtemp");
std::abort();
}
return templ;
}();
static const bool cleanup_registered = []
{
std::atexit(
[]
{
std::error_code ec; // best effort: a leftover directory is not a failure
std::filesystem::remove_all(private_temp_dir(), ec);
});
return true;
}();
(void)cleanup_registered;
return dir;
}
struct FatalRun
{
int status = -1; ///< the shell's: 134 for an abort
std::string out; ///< stdout and stderr
std::string log; ///< CHUNK_LOG_FILE
};
/// @brief Run the child of case @p which, under @p wrapper (a debugger's
/// command line, or nothing) and with the variables @p env in addition.
/// CHUNK_BREAK_ON_FAILURE is auto unless @p env sets it: one the user
/// exported does not change the outcome.
FatalRun run_child(const char* self, int which, std::string_view env = "", std::string_view wrapper = "")
{
const std::string base = private_temp_dir() + "/fatal." + std::to_string(which);
const std::string cmd = "ulimit -c 0; CHUNK_LOG=warn CHUNK_BREAK_ON_FAILURE=auto CHUNK_LOG_FILE=\"" + base +
".log\" " + std::string(env) + " timeout 120 " + std::string(wrapper) + " \"" +
std::string(self) + "\" --fatal " + std::to_string(which) + " > \"" + base + ".out\" 2>&1";
FatalRun run;
const int status = std::system(cmd.c_str());
run.status = (status != -1 && WIFEXITED(status)) ? WEXITSTATUS(status) : -1;
for (const auto& line : read_lines(base + ".out"))
{
run.out += line + "\n";
}
for (const auto& line : read_lines(base + ".log"))
{
run.log += line + "\n";
}
std::remove((base + ".out").c_str());
std::remove((base + ".log").c_str());
return run;
}
std::size_t count(const std::string& text, std::string_view what)
{
std::size_t occurrences = 0;
for (std::size_t pos = text.find(what); pos != std::string::npos; pos = text.find(what, pos + what.size()))
{
++occurrences;
}
return occurrences;
}
void check_fatal(const char* self)
{
constexpr int abort_status = 134; // 128 + SIGABRT, as the shell reports it
auto run = run_child(self, 0);
check(run.status == abort_status, "fatal: CHUNK_INVARIANT_FAILED aborts");
check(count(run.out, "In file '") == 1 && run.out.find("Inside function: ") != std::string::npos,
"fatal: location block on stderr");
check(run.out.find("value 7 complex (1-2i) bytes 0x0100000002000000") != std::string::npos,
"fatal: int, std::complex and a type with no formatter spelled");
check(run.out.find("--- Execution Backtrace ---") != std::string::npos, "fatal: backtrace on stderr");
check(run.log.find("[shrink_array][general][F][") != std::string::npos &&
run.log.find("] value 7 complex") != std::string::npos,
"fatal: the record reaches CHUNK_LOG_FILE");
if (g_fails != 0)
{
println("---- child 0 output ----\n{}---- log ----\n{}------------------------", run.out, run.log);
}
run = run_child(self, 1);
check(run.status == abort_status && count(run.out, "In file '") == 1 &&
count(run.out, "--- Execution Backtrace ---") == 1,
"fatal: 8 threads failing at once give one report");
run = run_child(self, 2);
check(run.status == abort_status && run.out.find("SINK fatal: to the sink 42") != std::string::npos &&
run.out.find("--- Execution Backtrace ---") != std::string::npos,
"fatal: the record reaches the program's sink, after the block");
run = run_child(self, 3);
// The first record the sink sees is the deprecation warning of
// FAST_ALLOC_TRACE (inherited from main), written while the
// configuration is read: the failure must not wait on that read.
check(run.status == abort_status && run.out.find("failure inside the sink, on \"") != std::string::npos,
"fatal: a failure inside the sink stops, even during the configuration (no deadlock: timeout 60 s)");
run = run_child(self, 5);
check(run.status == abort_status && run.out.find("[CRITICAL_FAILURE] allocator failure 6") != std::string::npos &&
run.out.find("--- Execution Backtrace ---") != std::string::npos &&
run.log.find("[shrink_array][general][F][") != std::string::npos,
"FAST_ALLOC_FATAL: the same fatal report (block, backtrace, CHUNK_LOG_FILE)");
// Forced on, without a debugger: the report, the line that says why, then
// SIGTRAP, which nothing handles, kills the child (128 + SIGTRAP).
run = run_child(self, 0, "CHUNK_BREAK_ON_FAILURE=1");
check(run.status == 128 + SIGTRAP && run.out.find("--- Execution Backtrace ---") != std::string::npos &&
run.out.find("CHUNK_BREAK_ON_FAILURE=1: stopping on SIGTRAP") != std::string::npos &&
run.out.find("--- Execution Backtrace ---") < run.out.find("stopping on SIGTRAP"),
"fatal: CHUNK_BREAK_ON_FAILURE=1 stops on SIGTRAP, after the report");
check(run_child(self, 5).out.find("stopping on SIGTRAP") == std::string::npos,
"fatal: no stop without a debugger (auto)");
run = run_child(self, 4);
if constexpr (shrink_array::build_config::any_check)
{
check(run.status == abort_status && run.out.find("[drain] check failed 5") != std::string::npos &&
run.out.find("carried on") == std::string::npos,
"CHUNK_CHECK_FAILED stops a check build");
}
else
{
check(run.status == 0 && run.log.find("[shrink_array][drain][E][") != std::string::npos &&
run.log.find("] check failed 5") != std::string::npos &&
run.out.find("carried on") != std::string::npos,
"CHUNK_CHECK_FAILED logs an error and carries on outside a check build");
}
}
// --- 10. The debugger detection ---------------------------------------------
void check_debugger_detection()
{
namespace fd = fast_alloc::logging::detail;
static_assert(fd::tracer_pid("Name:\tgdb\nState:\tS (sleeping)\nTracerPid:\t4242\nUid:\t1\n") == 4242);
constexpr std::string_view untraced = "Name:\tlog_validation\nUmask:\t0022\nPPid:\t12\nTracerPid:\t0\nUid:\t1\n";
check(fd::tracer_pid(untraced) == 0, "detection: TracerPid 0, no tracer");
check(fd::tracer_pid("Name:\tx\nPPid:\t1\nTracerPid: 77") == 77, "detection: spaces, last line with no newline");
check(fd::tracer_pid("Name:\tx\nPPid:\t1\n") == 0, "detection: no TracerPid line (other kernel, cut buffer)");
check(fd::tracer_pid("TracerPid:\t9\nTracerPid:\t0\n") == 0,
"detection: a process named \"TracerPid:\" is not its own tracer");
check(fd::tracer_pid("") == 0, "detection: an empty read");
check(fd::is_debugger_name("gdb\n") && fd::is_debugger_name("cuda-gdb\n") && fd::is_debugger_name("gdbserver\n") &&
fd::is_debugger_name("lldb\n") && fd::is_debugger_name("lldb-server\n") && fd::is_debugger_name("gdb"),
"detection: gdb, cuda-gdb, gdbserver, lldb, lldb-server are debuggers");
check(
!fd::is_debugger_name("strace\n") && !fd::is_debugger_name("ltrace\n") && !fd::is_debugger_name("perf\n") &&
!fd::is_debugger_name("rr\n") && !fd::is_debugger_name("tvdsvr\n") &&
!fd::is_debugger_name("tvdsvrmain\n") && !fd::is_debugger_name("totalview\n") &&
!fd::is_debugger_name("forge-backend\n") && !fd::is_debugger_name("gdb-wrapper\n") &&
!fd::is_debugger_name(""),
"detection: strace, ltrace, perf, rr, TotalView, DDT, a name merely starting with gdb, an empty read are not");
#if defined(__linux__)
// This process's own file, read as the fatal path reads it: TracerPid is
// in it, and with no tracer (ctest's case), no debugger is seen.
char status[4096];
const std::size_t len = fd::read_small_file("/proc/self/status", status, sizeof(status));
check(len > 0 && std::string_view(status, len).find("\nTracerPid:") != std::string_view::npos,
"detection: /proc/self/status read, with its TracerPid line");
check(fd::tracer_pid(std::string_view(status, len)) != 0 || !fd::debugger_attached(),
"detection: untraced, no debugger");
#endif
}
// --- With --debugger: the fatal child under gdb and strace --------------------
/// @brief True when @p a is found in @p text before @p b (both found).
bool before(const std::string& text, std::string_view a, std::string_view b)
{
const auto pa = text.find(a);
const auto pb = text.find(b);
return pa != std::string::npos && pb != std::string::npos && pa < pb;
}
int check_debuggers(const char* self, std::string_view gdb, std::string_view strace)
{
const std::string gdb_q = "\"" + std::string(gdb) + "\"";
// The detection is Linux's (TracerPid): elsewhere, no stop to look for.
constexpr bool linux_proc =
#if defined(__linux__)
true;
#else
false;
#endif
if (!linux_proc || gdb.empty() || std::system((gdb_q + " -nx -batch -ex quit > /dev/null 2>&1").c_str()) != 0)
{
println("SKIP: not Linux, or no gdb to run");
return 77;
}
// run, then the frames at the stop, then continue: the abort.
const std::string wrapper = gdb_q + " -nx -batch -ex run -ex bt -ex continue -ex kill --args";
auto run = run_child(self, 0, "", wrapper);
check(before(run.out, "--- Execution Backtrace ---", "debugger attached: stopping on SIGTRAP") &&
before(run.out, "debugger attached: stopping on SIGTRAP", "received signal SIGTRAP"),
"gdb: the report written, the line, then the stop on SIGTRAP");
const auto trap = run.out.find("received signal SIGTRAP");
const auto abort = run.out.find("received signal SIGABRT");
const auto frame = std::min({run.out.find("break_on_failure", trap), run.out.find("fatal_report", trap),
run.out.find("invariant_failed", trap)});
check(trap != std::string::npos && frame < abort, "gdb: a frame of the fatal path in the backtrace at the stop");
check(trap != std::string::npos && abort != std::string::npos && trap < abort, "gdb: continued, it aborts");
if (g_fails != 0)
{
println("---- gdb output ----\n{}--------------------", run.out);
}
run = run_child(self, 0, "CHUNK_BREAK_ON_FAILURE=0", wrapper);
check(run.out.find("SIGTRAP") == std::string::npos &&
run.out.find("received signal SIGABRT") != std::string::npos &&
run.out.find("--- Execution Backtrace ---") != std::string::npos,
"gdb, CHUNK_BREAK_ON_FAILURE=0: no stop, the abort");
if (!strace.empty())
{
// strace -f exits as its tracee did: 134 for the abort, 133 had it
// been a SIGTRAP.
run = run_child(self, 0, "", "\"" + std::string(strace) + "\" -f -o /dev/null");
check(run.status == 128 + SIGABRT && run.out.find("stopping on SIGTRAP") == std::string::npos,
"strace: traced but no debugger, the abort and no SIGTRAP");
}
else
{
println("no strace: its check is skipped");
}
println("{}", g_fails == 0 ? "PASS" : "FAILED");
return g_fails == 0 ? 0 : 1;
}
} // namespace
int main(int argc, char** argv)
{
if (argc > 2 && std::string_view(argv[1]) == "--fatal")
{
return run_fatal(std::atoi(argv[2]));
}
if (argc > 1 && std::string_view(argv[1]) == "--debugger")
{
return check_debuggers(argv[0], argc > 2 ? argv[2] : "", argc > 3 ? argv[3] : "");
}
// Before the first message: the configuration is read at it.
g_log_path = private_temp_dir() + "/shrink_log_validation." + std::to_string(::getpid()) + ".log";
std::remove(g_log_path.c_str());
setenv("CHUNK_LOG", "warn, rechunk=debug, verbose", 1);
setenv("FAST_ALLOC_TRACE", "1", 1); // a deprecated legacy switch: raises alloc to trace
setenv("CHUNK_LEDGER_REPORT", "1", 1); // a former report switch: raises ledger to info
unsetenv("CHUNK_ARENA_REPORT");
setenv("CHUNK_RECHUNK_CHURN", "1", 1); // no longer read: CHUNK_LOG=rechunk=debug
setenv("CHUNK_LOG_FILE", (private_temp_dir() + "/shrink_log_validation.%p.log").c_str(), 1); // %p: g_log_path
check_environment();
check_parse();
check_filter();
check_sink();
check_rate_limits();
check_truncation();
check_no_allocation();
check_threads();
check_fatal(argv[0]);
check_debugger_detection();
std::remove(g_log_path.c_str());
println("{}", g_fails == 0 ? "PASS" : "FAILED");
return g_fails == 0 ? 0 : 1;
}