-
Notifications
You must be signed in to change notification settings - Fork 320
/
Copy pathbsls_log.t.cpp
3914 lines (3332 loc) · 148 KB
/
bsls_log.t.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
// bsls_log.t.cpp -*-C++-*-
#include <bsls_log.h>
#include <bsls_bsltestutil.h>
#include <bsls_platform.h>
#include <fcntl.h>
#include <limits.h> // PATH_MAX on linux, INT_MAX
#include <stdio.h> // 'snprintf', '_snprintf'
#include <stdlib.h> // abort
#include <string.h> // strlen, strncpy
#include <sys/types.h> // struct stat[64]: required on Sun and Windows only
#include <sys/stat.h> // struct stat[64]: required on Sun and Windows only
#if defined(BSLS_PLATFORM_OS_WINDOWS)
# include <windows.h>
# include <io.h> // _dup2, _dup, _close
# define snprintf _snprintf
#else
# include <unistd.h>
# include <stdint.h> // SIZE_MAX. Cannot include on all Windows platforms.
#endif
using namespace BloombergLP;
// ============================================================================
// TEST PLAN
// ----------------------------------------------------------------------------
// Overview
// --------
// The component under test provides a global facility for low-level code to
// write log messages.
//
// Global Concerns:
//: o The test driver is robust w.r.t. reuse in other, similar components.
//: o By default, the 'platformDefaultMessageHandler' is used.
//: o Exceptions thrown in a log message handler are propagated.
//: o Precondition violations are detected in appropriate build modes.
//
// Global Assumptions:
//: o Setting, retrieving, and invoking the log message handler is thread-safe.
// ----------------------------------------------------------------------------
// MACROS
// [10] BSLS_LOG(severity, format, ...)
// [ 9] BSLS_LOG_SIMPLE(severity, message)
// [12] BSLS_LOG_FATAL(format, ...)
// [12] BSLS_LOG_ERROR(format, ...)
// [12] BSLS_LOG_WARN(format, ...)
// [12] BSLS_LOG_INFO(format, ...)
// [12] BSLS_LOG_DEBUG(format, ...)
// [12] BSLS_LOG_TRACE(format, ...)
//
// TYPES
// [ 4] typedef void (*LogMessageHandler)(severity, file, line, message);
//
// CLASS METHODS
// [ 7] static bsls::Log::LogMessageHandler logMessageHandler();
// [ 7] static void setLogMessageHandler(bsls::Log::LogMessageHandler);
// [11] static void setSeverityThreshold(bsls::LogSeverity::Enum );
// [11] static bsls::LogSeverity::Enum severityThreshold();
// [10] static void logFormattedMessage(severity, file, line, format, ...);
// [ 9] static void logMessage(severity, file, line, message);
// [ 6] static void platformDefaultMessageHandler(severity,file,line,message);
// [ 4] static void stdoutMessageHandler(severity, file, line, message);
// [ 4] static void stderrMessageHandler(severity, file, line, message);
// ----------------------------------------------------------------------------
// [ 5] Test Driver: 'fillBuffer(buffer, size)' and 'LargeTestData'
// [ 3] WINDOWS DEBUG MESSAGE SINK
// [ 2] TEST-DRIVER LOG MESSAGE HANDLER
// [ 1] STREAM REDIRECTION APPARATUS
// [13] USAGE EXAMPLES
// [ *] CONCERN: This test driver is reusable w/other, similar components.
// [ *] CONCERN: Exceptions thrown in a log message handler are propagated.
// [ *] CONCERN: Precondition violations are detected when enabled.
// [ 8] CONCERN: By default, the 'platformDefaultMessageHandler' is used.
// NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY
// FUNCTIONS, INCLUDING IOSTREAMS.
// ============================================================================
// STANDARD BSL ASSERT TEST FUNCTION
// ----------------------------------------------------------------------------
namespace {
int testStatus = 0;
void aSsErT(bool condition, const char *message, int line)
{
if (condition) {
printf("Error " __FILE__ "(%d): %s (failed)\n", line, message);
if (0 <= testStatus && testStatus <= 100) {
++testStatus;
}
}
}
} // close unnamed namespace
// ============================================================================
// STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT BSLS_BSLTESTUTIL_ASSERT
#define ASSERTV BSLS_BSLTESTUTIL_ASSERTV
#define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT
#define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally.
#define P BSLS_BSLTESTUTIL_P // Print identifier and value.
#define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLS_BSLTESTUTIL_L_ // current Line number
// ============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
// ----------------------------------------------------------------------------
typedef bsls::LogSeverity Severity;
#ifndef SIZE_MAX
#define SIZE_MAX (static_cast<size_t>(-1))
// 'SIZE_MAX' is only defined as part of C99, so it may not exist in some
// pre-C++11 compilers.
#endif
#ifdef BSLS_PLATFORM_OS_WINDOWS
static const size_t PATH_BUFFER_SIZE = MAX_PATH + 1;
#else
static const size_t PATH_BUFFER_SIZE = PATH_MAX + 1;
#endif
static const size_t WINDOWS_DEBUG_MESSAGE_SINK_BUFFER_SIZE = 4096;
// This represents the size of the buffer that will be used to store debug
// messages captured in the Windows debugger. This should generally be at
// least '4092' (i.e. 4096 - sizeof(DWORD)), since this is the maximum
// string size that 'OutputDebugString' will write.
static const char * const WINDOWS_SUBPROCESS_EVENT_NAME = "BSLS_LOG_TEST";
// This constant represents the name of the Windows 'Event' that will be
// used for communication between the main test case and its subprocess so
// that the 'OutputDebugString' functionality can be tested. Both
// processes attempt to create an 'Event' with the same name, and will
// therefore be able to communicate using this event.
static const size_t LOG_MESSAGE_SINK_BUFFER_SIZE = 4096;
// This represents the size of the buffers used by the class
// 'LogMessageSink' to store the file name and line number values received
// as part of the logging interface.
static const size_t OUTPUT_REDIRECTOR_BUFFER_SIZE = 4096;
// This represents the size of the buffer used by the class
// 'OutputRedirector' to store the captured values loaded in the 'stdout'
// and 'stderr' error streams.
// Keep the below in sync with 'bsls_log.cpp'
static const size_t WINDOWS_DEBUG_STACK_BUFFER_SIZE = 1024;
// This represents the size of the initial stack buffer used in the method
// 'bsls::Log::platformDefaultMessageHandler' when it is writing output to
// 'OutputDebugStringA'. Keep this in sync with 'bsls_log.cpp'
static const size_t LOG_FORMATTED_STACK_BUFFER_SIZE = 1024;
// This represents the size of the initial stack buffer used in the method
// 'bsls::Log::logFormattedMessage' when it is formatting its
// 'printf'-style output.
// Standard test driver globals:
static int test;
static bool verbose;
static bool veryVerbose;
static bool veryVeryVerbose;
static bool veryVeryVeryVerbose;
// ============================================================================
// GLOBAL TEST DATA
// ----------------------------------------------------------------------------
struct DefaultDataRow {
int d_sourceLine;
Severity::Enum d_severity;
const char *d_file;
int d_line;
const char *d_message;
const char *d_expected;
};
static
const DefaultDataRow DEFAULT_DATA[] = {
// This is a set of good, useful data that is the cross product of the sets
// of situations in which the file name string is empty or non-empty, the
// line is 0 or non-zero, and the message is empty or non-empty. The file
// name and message strings may also have 'printf'-style format specifiers
// to ensure that no unwanted formatting is being done.
//
// All normal values:
{L_,
Severity::e_WARN,
"Very VaLidF1%d%dLeN@me",
408743,
"Valid \n %fMessage String",
"WARN Very VaLidF1%d%dLeN@me:408743 Valid \n %fMessage String\n"},
// Empty message string:
{L_,
Severity::e_ERROR,
"Good File Name!%s.cpp",
2147483000,
"",
"ERROR Good File Name!%s.cpp:2147483000 \n"},
// Zero line number:
{L_,
Severity::e_FATAL,
"%filename.cpp",
0,
"Message String!",
"FATAL %filename.cpp:0 Message String!\n"},
// Zero line number, empty message:
{L_,
Severity::e_WARN,
"fi%ldename.cpp",
0,
"",
"WARN fi%ldename.cpp:0 \n"},
// Empty file name:
{L_,
Severity::e_WARN,
"",
83274892,
"Good MESSAGE STRING %x ~~~",
"WARN :83274892 Good MESSAGE STRING %x ~~~\n"},
// Empty file name, empty message string:
{L_,
Severity::e_WARN,
"",
93874829,
"",
"WARN :93874829 \n"},
// Empty file name, zero line number:
{L_,
Severity::e_WARN,
"",
0,
"Another Message :)",
"WARN :0 Another Message :)\n"},
// Empty file name, zero line number, empty message:
{L_,
Severity::e_WARN,
"",
0,
"",
"WARN :0 \n"},
};
static const size_t NUM_DEFAULT_DATA = sizeof(DEFAULT_DATA)
/ sizeof(DEFAULT_DATA[0]);
#ifdef BSLS_PLATFORM_OS_WINDOWS
// The Windows implementation of 'platformDefaultMessageHandler' has to format
// data to a stack-local buffer, and if it does not fit, it has to allocate a
// new buffer. We need to test data that has a length around the size of the
// buffer.
// What kind of final string lengths do we want to test for the Windows buffer?
// This describes the length of the *final* string, i.e. ":3 <message>\n".
const size_t WINDOWS_LARGE_DATA_LENGTHS[] = {
WINDOWS_DEBUG_STACK_BUFFER_SIZE - 5,
WINDOWS_DEBUG_STACK_BUFFER_SIZE - 4,
WINDOWS_DEBUG_STACK_BUFFER_SIZE - 3,
WINDOWS_DEBUG_STACK_BUFFER_SIZE - 2,
WINDOWS_DEBUG_STACK_BUFFER_SIZE - 1,
WINDOWS_DEBUG_STACK_BUFFER_SIZE,
WINDOWS_DEBUG_STACK_BUFFER_SIZE + 1,
WINDOWS_DEBUG_STACK_BUFFER_SIZE + 2,
WINDOWS_DEBUG_STACK_BUFFER_SIZE + 3,
WINDOWS_DEBUG_STACK_BUFFER_SIZE + 4,
WINDOWS_DEBUG_STACK_BUFFER_SIZE + 5
};
const size_t NUM_WINDOWS_LARGE_DATA_LENGTHS =
sizeof(WINDOWS_LARGE_DATA_LENGTHS)/sizeof(WINDOWS_LARGE_DATA_LENGTHS[0]);
#endif // BSLS_PLATFORM_OS_WINDOWS
// ============================================================================
// GLOBAL HELPER FUNCTIONS FOR TESTING
// ----------------------------------------------------------------------------
static void fillBuffer(char * const buffer, const size_t size)
// Fill the specified 'size' - 1 number of characters in the specified
// 'buffer' with a repeated sequence of ['A' - 'Z'], except for the last
// repetition in which the sequence will be truncated such that only
// 'size' - 1 total characters will have been written. Write a null byte
// to the final position in 'buffer' (index @ 'size' - 1). The behavior is
// undefined unless 'buffer' has at least 'size' bytes available.
{
// Fill the substitution buffer with ['A' .. 'Z'] looping. All of our
// systems use ASCII, so 'A' - 'Z' are contiguous.
const unsigned char numLetters = 26;
for(size_t i = 0; i < size - 1; ++i) {
buffer[i] = static_cast<char>('A' + i%numLetters);
}
buffer[size - 1] = '\0';
}
class LargeTestData {
// This class provides a mechanism for generating a test message that
// will result in output of an expected size when published from
// 'Log::stdoutMessageHandler', 'Log::stderrMessageHandler', or
// 'Log::platformDefaultMessageHandler'. Such large test data is important
// for white-box testing the output mechanisms in 'bsls_log' (which
// sometimes use stack buffers whose sizes are determined at compile time).
public:
// PUBLIC CONSTANTS
static const char *k_LOG_FORMAT_STRING; // Format string for which the
// 'LargeTeestData' is sized.
// Note that it is used by
// 'stdoutMessageHandler',
// 'stderrMessageHandler', and
// 'platformDefaultMessageHandler'
private:
// DATA
char *d_expectedOutput; // the expected logged output
// for 'message'
char *d_message; // the 'message' that, when
// logged, will generate
// the expected output length
public:
explicit LargeTestData(int expectedOutputLength,
bsls::LogSeverity::Enum severity,
const char *file,
int line);
// Create a large test data object that will provide a test message
// having expected output of the specified 'expectedOutputLength',
// when used with the 'stdoutMessageHandler', 'stderrMessageHandler',
// and 'platformDefaultMessageHandler' and suppling the specified
// 'severity', 'file', and 'line'.
~LargeTestData();
// Destroy this 'LargeTestData' object.
const char *message() const;
// Return a message which, when supplied to 'bsls::Log::logMessage'
// will result in an log record having the expected length supplied
// at construction.
const char *expectedOutput() const;
// Return the expected results of calling 'bsls::Log::LogMessage' and
// passing 'message' with the 'severity', 'file', and 'line' supplied
// at construction.
};
const char *LargeTestData::k_LOG_FORMAT_STRING = "%s %s:%d %s\n";
// This must be the same format string used by the
// 'stdoutMessageHandler', 'stderrMessageHandler', and
// 'platformDefaultMessageHandler' to result in 'LargeTestData'
// that generates appropriately sized messages.
LargeTestData::LargeTestData(int expectedOutputLength,
bsls::LogSeverity::Enum severity,
const char *file,
int line)
{
d_expectedOutput = static_cast<char *>(malloc(expectedOutputLength+2));
d_message = static_cast<char *>(malloc(expectedOutputLength+2));
if (!d_expectedOutput || !d_message) {
printf("Test driver error at %d. Allocation failed.", __LINE__);
abort();
}
int rc = snprintf(d_message,
expectedOutputLength,
k_LOG_FORMAT_STRING,
bsls::LogSeverity::toAscii(severity),
file,
line,
"");
#if defined(BSLS_PLATFORM_OS_WINDOWS)
if (-1 == rc) {
#else
if (rc >= expectedOutputLength) {
#endif
printf("Test driver error at %d. rc = %d\n", __LINE__, rc);
abort();
}
fillBuffer(d_message, expectedOutputLength - rc + 1);
rc = snprintf(d_expectedOutput,
expectedOutputLength+2,
k_LOG_FORMAT_STRING,
bsls::LogSeverity::toAscii(severity),
file,
line,
d_message);
if (rc != expectedOutputLength) {
printf("Test driver error at %d. rc = %d\n", __LINE__, rc);
abort();
}
}
inline
LargeTestData::~LargeTestData()
{
free(d_expectedOutput);
free(d_message);
}
const char *LargeTestData::message() const
{
return d_message;
}
const char *LargeTestData::expectedOutput() const
{
return d_expectedOutput;
}
// ============================================================================
// GLOBAL HELPER CLASSES FOR TESTING
// ----------------------------------------------------------------------------
#if defined(BSLS_PLATFORM_OS_WINDOWS) || defined(BSLS_PLATFORM_OS_DARWIN)
typedef struct stat StatType;
#else
typedef struct stat64 StatType;
#endif
inline int fstatFunc(int fd, StatType *buf)
{
#if defined(BSLS_PLATFORM_OS_WINDOWS) || defined(BSLS_PLATFORM_OS_DARWIN)
return fstat(fd, buf);
#else
return fstat64(fd, buf);
#endif
}
// =============================
// class WindowsDebugMessageSink
// =============================
class WindowsDebugMessageSink {
// This class provides a mechanism to allow the current process to act as a
// Windows debugger, capturing all logs written to the 'OutputDebugString'
// Windows API function by other processes.
private:
// TYPES
union SharedMemoryData {
unsigned char d_rawData[4096];
struct InterpretedData {
unsigned long d_pid;
char d_message[4096 - sizeof(unsigned long)];
} d_interpretedData;
};
// DATA
bool d_enabled; // are we enabled?
unsigned long d_expectedPid; // 'DWORD': our target PID
void *d_dbWinMutexHandle; // 'HANDLE' to 'DBWin' mutex
void *d_dbWinDataReadyHandle; // 'HANDLE' to Data Ready Event
void *d_dbWinBufferReadyHandle; // 'HANDLE' to Buffer Ready
void *d_dbWinBufferHandle; // 'HANDLE' to Data Buffer
SharedMemoryData *d_sharedData_p; // local mapping of data buffer
char d_localBuffer[WINDOWS_DEBUG_MESSAGE_SINK_BUFFER_SIZE];
private:
// NOT IMPLEMENTED
WindowsDebugMessageSink(const WindowsDebugMessageSink&); // = delete;
WindowsDebugMessageSink& operator=(
const WindowsDebugMessageSink&); // = delete;
public:
// CREATORS
WindowsDebugMessageSink();
// Create a 'WindowsDebugMessageSink' object that does not hold any
// OS-provided handles.
~WindowsDebugMessageSink();
// Destroy this object and de-register this process as the Windows
// debugger.
// MANIPULATORS
void disable();
// De-register this process as the Windows debugger. The behavior is
// undefined unless this function is called at most once during the
// life of this object.
bool enable(const unsigned long timeoutMilliseconds);
// Register this object as the Windows debugger. If a log message is
// being written, block until this object can be safely registered or
// until the specified 'timeoutMilliseconds' number of milliseconds
// have passed. Return 'true' if this object has been successfully
// enabled, or return 'false' in case of a timeout or some other error.
// The behavior is undefined unless unless this function is called at
// most once during the life of this object.
void setTargetProcessId(const unsigned long pid);
// Set this object to accept only debug messages of processes with the
// specified 'pid'. Messages from other processes will be discarded.
// The behavior is undefined unless 'pid' is non-zero.
bool wait(const unsigned long timeoutMilliseconds);
// Block until a debug message originating from the process with the
// PID specified in 'setTargetProcessID' or until the specified
// 'timeoutMilliseconds' have elapsed. Return 'true' if data was found
// and can be inspected through a later call to 'message'. Return
// 'false' if a timeout occurs or if some other error occurs. The
// behavior is undefined unless 'enable' has been successfully called
// and 'setTargetProcessId' has been called.
// ACCESSORS
const char *message();
// Return the null-terminated message stored by the last call to
// 'wait', if that call was successful. The behavior is undefined
// unless 'wait' has been called and the last call to 'wait' was
// successful.
};
#ifdef BSLS_PLATFORM_OS_WINDOWS
// In non-Windows builds, this class will simply have no implemented methods.
// The class definition is kept in place under non-Windows builds for simple
// consistency reasons.
// CREATORS
WindowsDebugMessageSink::WindowsDebugMessageSink()
: d_enabled(false)
, d_expectedPid(0)
, d_dbWinMutexHandle(NULL) //HANDLE
, d_dbWinDataReadyHandle(NULL)
, d_dbWinBufferReadyHandle(NULL)
, d_dbWinBufferHandle(NULL)
, d_sharedData_p(NULL)
{
d_localBuffer[0] = '\0';
}
WindowsDebugMessageSink::~WindowsDebugMessageSink()
{
disable();
}
// MANIPULATORS
void WindowsDebugMessageSink::disable()
{
if(!d_enabled) return; // RETURN
if(d_sharedData_p) {
UnmapViewOfFile(d_sharedData_p);
d_sharedData_p = NULL;
}
if(d_dbWinBufferHandle) {
CloseHandle(d_dbWinBufferHandle);
d_dbWinBufferHandle = NULL;
}
if(d_dbWinBufferReadyHandle) {
CloseHandle(d_dbWinBufferReadyHandle);
d_dbWinBufferReadyHandle = NULL;
}
if(d_dbWinDataReadyHandle) {
CloseHandle(d_dbWinDataReadyHandle);
d_dbWinDataReadyHandle = NULL;
}
if(d_dbWinMutexHandle) {
// If, for whatever reason the mutex is still held by us, we should
// release it. This call is harmless if we do not own the mutex:
ReleaseMutex(d_dbWinMutexHandle);
CloseHandle(d_dbWinMutexHandle);
d_dbWinMutexHandle = NULL;
}
d_enabled = false;
}
bool WindowsDebugMessageSink::enable(const unsigned long timeoutMilliseconds)
{
// First, we attempt to get a handle to the possibly-already-existing
// DBWinMutex. We only need the 'SYNCHRONIZE' permission. We use the 'A'
// version so that we can pass an ASCII string for the name.
d_dbWinMutexHandle = OpenMutexA(SYNCHRONIZE, FALSE, "DBWinMutex");
if(!d_dbWinMutexHandle) {
// If the mutex did not exist, we must create it. Why not call
// 'CreateMutexA' initially? Simply because if the mutex exists, it
// will be opened in 'MUTEX_ALL_ACCESS' mode, which is not what we want
// since we may not have admin access.
d_dbWinMutexHandle = CreateMutexA(NULL, FALSE, "DBWinMutex");
if(!d_dbWinMutexHandle) {
disable();
return false; // RETURN
}
}
// Suppose that some program is currently executing 'OutputDebugString',
// while we are attempting to do this setup. There are various issues with
// allowing this to occur, such as the fact that we may find that an event
// does not exist and then the event may be created by the logging process
// before we have a chance to create it. If this happens, our call to
// 'CreateEventA' may fail, since calling the Create* functions when the
// item already exists requests the 'ALL_ACCESS' permission types, which we
// will not be able to get. There is no way to prevent this when initially
// retrieving the mutex; the best we can do is first call 'OpenMutexA' and
// hope for the best. However, we can solve this with the later calls once
// we have the mutex, since 'OutputDebugString' will block until it gets
// the mutex. Other debuggers may cause us problems if they do not respect
// the mutex, but there is really nothing we can do about this.
const unsigned long oldTimeMilliseconds = GetTickCount();
const unsigned long waitResult = WaitForSingleObject(d_dbWinMutexHandle,
timeoutMilliseconds);
if(waitResult == WAIT_TIMEOUT || waitResult == WAIT_FAILED) {
return false; // RETURN
} else if(waitResult == WAIT_ABANDONED) {
// 'WAIT_ABANDONED' means that the owner of the mutex terminated before
// the mutex was released. We should just try to get the mutex
// ourselves, since we don't rely on the state of the buffer itself.
const unsigned long timeDiff = GetTickCount() - oldTimeMilliseconds;
if(timeDiff > timeoutMilliseconds) {
return false; // RETURN
}
const unsigned long newTimeoutMilliseconds = timeoutMilliseconds
- timeDiff;
if(WaitForSingleObject(d_dbWinMutexHandle, newTimeoutMilliseconds)
!= WAIT_OBJECT_0) {
return false; // RETURN
}
}
// If we reached this point, we have gotten the WAIT_OBJECT_0 return value
// and we now own the mutex. We must be sure to release it whenever we
// can.
// Now we will attempt to retrieve a handle to the 'DBWIN_DATA_READY'
// event, which is what 'OutputDebugString' uses to signal that it has
// successfully written its data to the buffer. We only need the
// 'SYNCHRONIZE' permission because we are not responsible for setting the
// data ready event.
d_dbWinDataReadyHandle = OpenEventA(SYNCHRONIZE,
FALSE,
"DBWIN_DATA_READY");
if(!d_dbWinDataReadyHandle) {
// If we have to create the event, we do not want to accidentally
// signal to ourselves that the data is ready until OutputDebugString
// sets it. Therefore, the initial state (third parameter) is 'FALSE'.
d_dbWinDataReadyHandle = CreateEventA(NULL,
FALSE,
FALSE,
"DBWIN_DATA_READY");
if(!d_dbWinDataReadyHandle) {
ReleaseMutex(d_dbWinMutexHandle);
disable();
return false; // RETURN
}
}
// Next, the DBWIN_BUFFER_READY event:
d_dbWinBufferReadyHandle = OpenEventA(EVENT_MODIFY_STATE,
FALSE,
"DBWIN_BUFFER_READY");
if(!d_dbWinBufferReadyHandle) {
// If we have to create the event, we do not want to signal that the
// buffer is ready until we are completely sure everything is ready.
// Therefore, the initial state (third parameter) is 'FALSE'.
d_dbWinBufferReadyHandle = CreateEventA(NULL,
FALSE,
FALSE,
"DBWIN_BUFFER_READY");
if(!d_dbWinBufferReadyHandle) {
ReleaseMutex(d_dbWinMutexHandle);
disable();
return false; // RETURN
}
}
// Finally, we must attempt to get a handle to the file mapping object:
d_dbWinBufferHandle = OpenFileMappingA(FILE_MAP_READ,
FALSE,
"DBWIN_BUFFER");
if(!d_dbWinBufferHandle) {
// If we have to create the event, we do not want to signal that the
// buffer is ready until we are completely sure everything is ready.
// Therefore, the initial state (third parameter) is 'FALSE'.
d_dbWinBufferHandle = CreateFileMappingA(INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
sizeof(SharedMemoryData),
"DBWIN_BUFFER");
if(!d_dbWinBufferHandle) {
ReleaseMutex(d_dbWinMutexHandle);
disable();
return false; // RETURN
}
}
d_sharedData_p = static_cast<SharedMemoryData*>(
MapViewOfFile(d_dbWinBufferHandle,
FILE_MAP_READ,
0,
0,
0));
if(!d_sharedData_p) {
ReleaseMutex(d_dbWinMutexHandle);
disable();
return false; // RETURN
}
// Finally, now that everything is ready, we will release the mutex and
// signal that the buffer is ready:
ReleaseMutex(d_dbWinMutexHandle);
SetEvent(d_dbWinBufferReadyHandle);
d_enabled = true;
return true;
}
void WindowsDebugMessageSink::setTargetProcessId(const unsigned long pid)
{
d_expectedPid = pid;
}
bool WindowsDebugMessageSink::wait(const unsigned long timeoutMilliseconds)
{
// Implementation note: The functionality in this class, including this
// function, can have a much wider contract than it currently does. The
// contract was narrowed because the extra flexibility wasn't being used
// so there was no need to add complexity to the test driver. If this
// class is expanded, the contract (and test cases) should be widened to
// allow a zero-PID being like a wildcard PID, as well as the ability to
// call 'enable' and 'disable' as many times as one wants.
if(!d_enabled) {
// It is too harmful to let this slide. Even in non-assert mode, it is
// worth checking our state.
ASSERT(d_enabled);
return false; // RETURN
}
const unsigned long oldTimeMilliseconds = GetTickCount();
bool keepGoing = true;
while(keepGoing) {
unsigned long timeDiff = GetTickCount() - oldTimeMilliseconds;
if(timeDiff > timeoutMilliseconds) {
return false; // RETURN
}
unsigned long newTimeoutMilliseconds = timeoutMilliseconds - timeDiff;
if(WaitForSingleObject(d_dbWinDataReadyHandle, newTimeoutMilliseconds)
!= WAIT_OBJECT_0) {
return false; // RETURN
}
// We need to hold the mutex to ensure that we have a consistent buffer
// while we are reading the data.
timeDiff = GetTickCount() - oldTimeMilliseconds;
if(timeDiff > timeoutMilliseconds) {
return false; // RETURN
}
newTimeoutMilliseconds = timeoutMilliseconds - timeDiff;
if(WaitForSingleObject(d_dbWinMutexHandle, newTimeoutMilliseconds)
!= WAIT_OBJECT_0) {
// In this case, we want to ignore the 'WAIT_ABANDONED' value
// because if the mutex was abandoned, the buffer will probably be
// invalid.
return false; // RETURN
}
if(d_expectedPid == 0 ||
d_expectedPid == d_sharedData_p->d_interpretedData.d_pid) {
strncpy(d_localBuffer,
d_sharedData_p->d_interpretedData.d_message,
WINDOWS_DEBUG_MESSAGE_SINK_BUFFER_SIZE - 1);
d_localBuffer[WINDOWS_DEBUG_MESSAGE_SINK_BUFFER_SIZE - 1] = '\0';
keepGoing = false; // We must use the loop to break us since we
// want to release the mutex.
}
ReleaseMutex(d_dbWinMutexHandle);
SetEvent(d_dbWinBufferReadyHandle);
}
return true;
}
// ACCESSORS
const char *WindowsDebugMessageSink::message()
{
ASSERT(d_enabled);
return d_localBuffer;
}
#endif // defined(BSLS_PLATFORM_OS_WINDOWS)
// ====================
// class LogMessageSink
// ====================
struct LogMessageSink {
// This struct provides a namespace for a utility function,
// 'testMessageHandler', which is a valid log message handler
// ('bsls::Log::LogMessageHandler') that will simply copy all arguments
// into a set of 'public' 'static' data members.
// This class is designed as fully static (instead of using a singleton) in
// order to more easily support registration of the log message handler.
public:
// PUBLIC CLASS DATA
static bool s_hasBeenCalled; // have we been called
// since the last
// reset?
static bsls::LogSeverity::Enum
s_severity; // severity of message
static char s_file[LOG_MESSAGE_SINK_BUFFER_SIZE]; // file name buffer
static int s_line; // line number
static char s_message[LOG_MESSAGE_SINK_BUFFER_SIZE]; // message buffer
// CLASS METHODS
static void reset();
// Set 's_hasBeenCalled' to 'false', write a null byte to the beginning
// of 's_file', set 's_line' to 0, and write a null byte to the
// beginning of 's_message'.
static void testMessageHandler(bsls::LogSeverity::Enum severity,
const char *file,
int line,
const char *message);
// Copy the specified 'severity', 'file', 'line', and 'message' to the
// correspondng public data members of this 'struct'. The behavior is
// undefined unless 'line >= 0'.
};
// PUBLIC CLASS DATA
bool LogMessageSink::s_hasBeenCalled = false;
char LogMessageSink::s_file[LOG_MESSAGE_SINK_BUFFER_SIZE] = {'\0'};
int LogMessageSink::s_line = 0;
char LogMessageSink::s_message[LOG_MESSAGE_SINK_BUFFER_SIZE] = {'\0'};
Severity::Enum LogMessageSink::s_severity =
Severity::e_FATAL;
// CLASS METHODS
void LogMessageSink::reset()
{
s_hasBeenCalled = false;
s_severity = bsls::LogSeverity::e_FATAL;
s_file[0] = '\0';
s_line = 0;
s_message[0] = '\0';
}
void LogMessageSink::testMessageHandler(bsls::LogSeverity::Enum severity,
const char *file,
int line,
const char *message)
{
ASSERT(file);
ASSERT(line >= 0);
ASSERT(message);
s_hasBeenCalled = true;
s_severity = severity;
strncpy(s_file, file, LOG_MESSAGE_SINK_BUFFER_SIZE);
s_line = line;
strncpy(s_message, message, LOG_MESSAGE_SINK_BUFFER_SIZE);
// Just to be safe.
s_file [LOG_MESSAGE_SINK_BUFFER_SIZE - 1] = '\0';
s_message[LOG_MESSAGE_SINK_BUFFER_SIZE - 1] = '\0';
}
// ======================
// class OutputRedirector
// ======================
// Temp file creation and output redirection re-purposed from the pre-existing
// module in 'bsls_bsltestutil.t.cpp'.
class OutputRedirector {
// This class provides a facility for redirecting 'stdout' and 'stderr' to
// temporary files, retrieving output from the respective temporary file
// and comparing the output to user-supplied character buffers. An
// 'OutputRedirector' object can be in an un-redirected state or a
// redirected state. If it is a redirected state, it will redirect either
// 'stdout' or 'stderr', but not both simultaneously. An
// 'OutputRedirector' object has the concept of a scratch buffer, where
// output captured from the process' 'stdout' or 'stderr' stream is stored
// when the 'OutputRedirector' object is in the redirected state.
// Throughout this class, the term "captured output" refers to data that
// has been written to the 'stdout' or 'stderr' stream and is waiting to be
// loaded into the scratch buffer. Each time the 'load' method is called,
// the scratch buffer is truncated, and the captured output is moved into
// the scratch buffer. When this is done, there is no longer any captured
// output.
public:
// TYPES
enum Stream {
// The 'enum' 'Stream' represents the specific stream which our object
// is responsible for redirecting.
STDOUT_STREAM,
STDERR_STREAM
};
private:
// DATA
char d_fileName[PATH_BUFFER_SIZE]; // name of temporary capture file
char d_outputBuffer[OUTPUT_REDIRECTOR_BUFFER_SIZE];
// 'd_outputBuffer' is the buffer that will hold the captured output.
const Stream d_stream; // the stream for which this
// object is responsible
bool d_isRedirectingFlag; // Is this object currently
// redirecting?
bool d_isFileCreatedFlag; // has a temp file been created?
bool d_isOutputReadyFlag; // has output been read from temp
// file?
size_t d_outputSize; // size of output loaded into
// 'd_outputBuffer'
StatType d_originalStat; // status information for
// 'stdout' or 'stderr' just
// before redirection
int d_duplicatedOriginalFd; // a file descriptor that is
// associated with a duplicate of
// the original target of the
// redirected stream. This is
// made by calling 'dup' on the
// original stream before any
// redirection happens
// PRIVATE MANIPULATORS
void cleanup();
// If the redirector is in a redirected state, restore the original
// target of the redirected stream. If the temporary file has been
// created, delete it.
void cleanupFiles();
// Delete the temporary file, if it has been created.
bool generateTempFileName();
// Load into 'd_fileName' a file name string corresponding to the name
// of a valid temp file on the system. Return 'true' if the name was
// successfully loaded, or 'false' otherwise.
private:
// NOT IMPLEMENTED
OutputRedirector(const OutputRedirector&); // = delete;