forked from PlatformLab/NanoLog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Log.cc
2077 lines (1799 loc) · 71.1 KB
/
Log.cc
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
/* Copyright (c) 2017-2020 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <algorithm>
#include <bits/algorithmfwd.h>
#include <regex>
#include <vector>
#include "Log.h"
#include "GeneratedCode.h"
namespace NanoLogInternal {
/**
* Friendly names for each #LogLevel value.
* Keep this in sync with the LogLevel enum in NanoLog.h.
*/
static const char* logLevelNames[] = {"(none)", "ERROR", "WARNING",
"NOTICE", "DEBUG"};
/**
* Insert a checkpoint into an output buffer. This operation is fairly
* expensive so it is typically performed once per new log file.
*
* \param out[in/out]
* Output array to insert the checkpoint into
* \param outLimit
* Pointer to the end of out (i.e. first invalid byte to write to)
*
* \return
* True if operation succeed, false if there's not enough space
*/
bool
Log::insertCheckpoint(char **out, char *outLimit, bool writeDictionary) {
if (static_cast<uint64_t>(outLimit - *out) < sizeof(Checkpoint))
return false;
Checkpoint *ck = reinterpret_cast<Checkpoint*>(*out);
*out += sizeof(Checkpoint);
ck->entryType = Log::EntryType::CHECKPOINT;
ck->rdtsc = PerfUtils::Cycles::rdtsc();
ck->unixTime = std::time(nullptr);
ck->cyclesPerSecond = PerfUtils::Cycles::getCyclesPerSec();
ck->newMetadataBytes = ck->totalMetadataEntries = 0;
if (!writeDictionary)
return true;
#ifdef PREPROCESSOR_NANOLOG
long int bytesWritten = GeneratedFunctions::writeDictionary(*out, outLimit);
if (bytesWritten == -1) {
// roll back and exit
*out -= sizeof(Checkpoint);
return false;
}
*out += bytesWritten;
ck->newMetadataBytes = static_cast<uint32_t>(bytesWritten);
ck->totalMetadataEntries = static_cast<uint32_t>(
GeneratedFunctions::numLogIds);
#endif // PREPROCESSOR_NANOLOG
return true;
}
/**
* Encoder constructor. The construction of an Encoder should logically
* correlate with the start of a new log file as it will embed unique metadata
* information at the beginning of log file/buffer.
*
* \param buffer
* Buffer to encode log messages and metadata to
* \param bufferSize
* The number of bytes usable within the buffer
* \param skipCheckpoint
* Optional parameter to skip embedding metadata information at the
* beginning of the buffer. This parameter should never bet set except
* in unit tests.
*/
Log::Encoder::Encoder(char *buffer,
size_t bufferSize,
bool skipCheckpoint,
bool forceDictionaryOutput)
: backing_buffer(buffer)
, writePos(buffer)
, endOfBuffer(buffer + bufferSize)
, lastBufferIdEncoded(-1)
, currentExtentSize(nullptr)
, encodeMissDueToMetadata(0)
, consecutiveEncodeMissesDueToMetadata(0)
{
assert(buffer);
// Start the buffer off with a checkpoint
if (skipCheckpoint && !forceDictionaryOutput)
return;
#ifdef PREPROCESSOR_NANOLOG
bool writeDictionary = true;
#else
bool writeDictionary = forceDictionaryOutput;
#endif
// In virtually all cases, our output buffer should have enough
// space to store the dictionary. If not, we fail in place.
if (!insertCheckpoint(&writePos, endOfBuffer, writeDictionary)) {
fprintf(stderr, "Internal Error: Not enough space allocated for "
"dictionary file.\r\n");
exit(-1);
}
}
/**
* Given a vector of StaticLogInfo and a starting index, encode all the static
* log information into a partial dictionary for the Decompressor to use.
*
* \param[in/out] currentPosition
* Starting/Ending index
* \param allMetadata
* All the static log information encountered so far
*
* \return
* Number of bytes encoded in the dictionary
*/
uint32_t
Log::Encoder::encodeNewDictionaryEntries(uint32_t& currentPosition,
std::vector<StaticLogInfo> allMetadata)
{
char *bufferStart = writePos;
if (sizeof(DictionaryFragment) >=
static_cast<uint32_t>(endOfBuffer - writePos))
return 0;
DictionaryFragment *df = reinterpret_cast<DictionaryFragment*>(writePos);
writePos += sizeof(DictionaryFragment);
df->entryType = EntryType::LOG_MSGS_OR_DIC;
while (currentPosition < allMetadata.size()) {
StaticLogInfo &curr = allMetadata.at(currentPosition);
size_t filenameLength = strlen(curr.filename) + 1;
size_t formatLength = strlen(curr.formatString) + 1;
size_t nextDictSize = sizeof(CompressedLogInfo)
+ filenameLength
+ formatLength;
// Not enough space, break out!
if (nextDictSize >= static_cast<uint32_t>(endOfBuffer - writePos))
break;
CompressedLogInfo *cli = reinterpret_cast<CompressedLogInfo*>(writePos);
writePos += sizeof(CompressedLogInfo);
cli->severity = curr.severity;
cli->linenum = curr.lineNum;
cli->filenameLength = static_cast<uint16_t>(filenameLength);
cli->formatStringLength = static_cast<uint16_t>(formatLength);
memcpy(writePos, curr.filename, filenameLength);
memcpy(writePos + filenameLength, curr.formatString, formatLength);
writePos += filenameLength + formatLength;
++currentPosition;
}
df->newMetadataBytes = 0x3FFFFFFF & static_cast<uint32_t>(
writePos - bufferStart);
df->totalMetadataEntries = currentPosition;
return df->newMetadataBytes;
}
#ifdef PREPROCESSOR_NANOLOG
/**
* Interprets the uncompressed log messages (created by the compile-time
* generated code) contained in the *from buffer and compresses them to
* the internal buffer. The encoded data can later be retrieved via swapBuffer()
*
* \param from
* A buffer containing the uncompressed log message created by the
* compile-time generated code
* \param nbytes
* Maximum number of bytes that can be extracted from the *from buffer
* \param bufferId
* The runtime thread/StagingBuffer id to associate the logs with
* \param newPass
* Indicates that this encoding correlates with starting a new pass
* through the runtime StagingBuffers. In other words, this should be true
* on the first invocation of this function after the runtime has checked
* and encoded all the StagingBuffers at least once.
* \param[out] numEventsCompressed
* adds the number of log messages processed in this invocation
*
* \return
* The number of bytes read from *from. A value of 0 indicates there is
* insufficient space in the internal buffer to fit the compressed message.
*/
long
Log::Encoder::encodeLogMsgs(char *from,
uint64_t nbytes,
uint32_t bufferId,
bool newPass,
uint64_t *numEventsCompressed)
{
if (!encodeBufferExtentStart(bufferId, newPass))
return 0;
uint64_t lastTimestamp = 0;
long remaining = nbytes;
long numEventsProcessed = 0;
char *bufferStart = writePos;
while (remaining > 0) {
auto *entry = reinterpret_cast<UncompressedEntry*>(from);
if (entry->entrySize > remaining) {
if (entry->entrySize < (NanoLogConfig::STAGING_BUFFER_SIZE/2))
break;
GeneratedFunctions::LogMetadata &lm
= GeneratedFunctions::logId2Metadata[entry->fmtId];
fprintf(stderr, "ERROR: Attempting to log a message that is %u "
"bytes while the maximum allowable size is %u.\r\n"
"This occurs for the log message %s:%u '%s'\r\n",
entry->entrySize,
NanoLogConfig::STAGING_BUFFER_SIZE/2,
lm.fileName, lm.lineNumber, lm.fmtString);
}
// Check for free space using the worst case assumption that
// none of the arguments compressed and there are as many Nibbles
// as there are data bytes.
uint32_t maxCompressedSize = downCast<uint32_t>(2*entry->entrySize
+ sizeof(Log::UncompressedEntry));
if (maxCompressedSize > (endOfBuffer - writePos))
break;
compressLogHeader(entry, &writePos, lastTimestamp);
lastTimestamp = entry->timestamp;
size_t argBytesWritten =
GeneratedFunctions::compressFnArray[entry->fmtId](entry, writePos);
writePos += argBytesWritten;
remaining -= entry->entrySize;
from += entry->entrySize;
++numEventsProcessed;
}
assert(currentExtentSize);
uint32_t currentSize;
std::memcpy(¤tSize, currentExtentSize, sizeof(uint32_t));
currentSize += downCast<uint32_t>(writePos - bufferStart);
std::memcpy(currentExtentSize, ¤tSize, sizeof(uint32_t));
if (numEventsCompressed)
*numEventsCompressed += numEventsProcessed;
return nbytes - remaining;
}
#endif // PREPROCESSOR_NANOLOG
/**
* Compresses a *from buffer filled with UncompressedEntry's and their
* arguments to an internal buffer. The encoded data can then later be retrieved
* via swapBuffer().
*
* This function is specialized for the non-preprocessor version of NanoLog and
* requires a dictionary mapping logId's to static log information to be
* explicitly passed in.
*
* \param from
* A buffer containing the uncompressed log message created by the
* the non-preprocessor version of NanoLog
* \param nbytes
* Maximum number of bytes that can be extracted from the *from buffer
* \param bufferId
* The runtime thread/StagingBuffer id to associate the logs with
* \param newPass
* Indicates that this encoding correlates with starting a new pass
* through the runtime StagingBuffers. In other words, this should be true
* on the first invocation of this function after the runtime has checked
* and encoded all the StagingBuffers at least once.
* \param[out] numEventsCompressed
* adds the number of log messages processed in this invocation
*
* \return
* The number of bytes read from *from. A value of 0 indicates there is
* insufficient space in the internal buffer to fit the compressed message.
*/
long
Log::Encoder::encodeLogMsgs(char *from,
uint64_t nbytes,
uint32_t bufferId,
bool newPass,
std::vector<StaticLogInfo> dictionary,
uint64_t *numEventsCompressed)
{
if (!encodeBufferExtentStart(bufferId, newPass))
return 0;
uint64_t lastTimestamp = 0;
long remaining = nbytes;
long numEventsProcessed = 0;
char *bufferStart = writePos;
while (remaining > 0) {
auto *entry = reinterpret_cast<UncompressedEntry*>(from);
// New log entry that we have not observed yet
if (dictionary.size() <= entry->fmtId) {
++encodeMissDueToMetadata;
++consecutiveEncodeMissesDueToMetadata;
// If we miss a whole bunch, then we start printing out errors
if (consecutiveEncodeMissesDueToMetadata % 1000 == 0) {
fprintf(stderr, "NanoLog Error: Metadata missing for a dynamic "
"log message (id=%u) during compression. If "
"you are using Preprocessor NanoLog, there is "
"be a problem with your integration (static "
"logs detected=%lu).\r\n",
entry->fmtId,
GeneratedFunctions::numLogIds);
}
break;
}
consecutiveEncodeMissesDueToMetadata = 0;
#ifdef ENABLE_DEBUG_PRINTING
printf("Trying to encode fmtId=%u, size=%u, remaining=%ld\r\n",
entry->fmtId, entry->entrySize, remaining);
printf("\t%s\r\n", dictionary.at(entry->fmtId).formatString);
#endif
if (entry->entrySize > remaining) {
if (entry->entrySize < (NanoLogConfig::STAGING_BUFFER_SIZE/2))
break;
StaticLogInfo &info = dictionary.at(entry->fmtId);
fprintf(stderr, "NanoLog ERROR: Attempting to log a message that "
"is %u bytes while the maximum allowable size is "
"%u.\r\n This occurs for the log message %s:%u '%s'"
"\r\n",
entry->entrySize,
NanoLogConfig::STAGING_BUFFER_SIZE/2,
info.filename, info.lineNum, info.formatString);
}
// Check for free space using the worst case assumption that
// none of the arguments compressed and there are as many Nibbles
// as there are data bytes.
uint32_t maxCompressedSize = downCast<uint32_t>(2*entry->entrySize
+ sizeof(Log::UncompressedEntry));
if (maxCompressedSize > (endOfBuffer - writePos))
break;
compressLogHeader(entry, &writePos, lastTimestamp);
lastTimestamp = entry->timestamp;
StaticLogInfo &info = dictionary.at(entry->fmtId);
#ifdef ENABLE_DEBUG_PRINTING
printf("\r\nCompressing \'%s\' with info.id=%d\r\n",
info.formatString, entry->fmtId);
#endif
char *argData = entry->argData;
info.compressionFunction(info.numNibbles, info.paramTypes,
&argData, &writePos);
remaining -= entry->entrySize;
from += entry->entrySize;
++numEventsProcessed;
}
assert(currentExtentSize);
uint32_t currentSize;
std::memcpy(¤tSize, currentExtentSize, sizeof(uint32_t));
currentSize += downCast<uint32_t>(writePos - bufferStart);
std::memcpy(currentExtentSize, ¤tSize, sizeof(uint32_t));
if (numEventsCompressed)
*numEventsCompressed += numEventsProcessed;
return nbytes - remaining;
}
/**
* Internal function that encodes a marker indicating that all log messages
* after this point (but after the next marker) belong to a particular buffer.
* This is only used in encodeLogMsgs, but is separated out to allow for easy
* unit testing with its counterpart in Decoder.
*
* \param bufferId
* Buffer id to encode in the extent
* \param newPass
* Indicates whether this buffer change also correlates with the start of
* a new pass through the runtime StagingBuffers by the caller
* \return
* Whether the operation completed successfully (true) or failed due to
* lack of space in the internal buffer (false)
*/
bool
Log::Encoder::encodeBufferExtentStart(uint32_t bufferId, bool newPass)
{
// For size check, assume the worst case of no compression on bufferId
char *writePosStart = writePos;
if (sizeof(BufferExtent) + sizeof(bufferId) >
static_cast<size_t>(endOfBuffer - writePos))
return false;
BufferExtent *tc = reinterpret_cast<BufferExtent*>(writePos);
writePos += sizeof(BufferExtent);
tc->entryType = EntryType::BUFFER_EXTENT;
tc->wrapAround = newPass;
if (bufferId < (1<<4)) {
tc->isShort = true;
tc->threadIdOrPackNibble = 0x0F & bufferId;
} else {
tc->isShort = false;
tc->threadIdOrPackNibble = 0x0F & BufferUtils::pack<uint32_t>(
&writePos, bufferId);
}
tc->length = downCast<uint32_t>(writePos - writePosStart);
currentExtentSize = &(tc->length);
lastBufferIdEncoded = bufferId;
return true;
}
/**
* Retrieve the number of bytes encoded in the internal buffer
*
* \return
* Number of bytes encoded in the internal buffer
*/
size_t
Log::Encoder::getEncodedBytes() {
return writePos - backing_buffer;
}
/**
* Releases the internal buffer and replaces it with a different one.
*
* \param inBuffer
* the new buffer to swap in
* \param inSize
* the amount of free space usable in the buffer
* \param[out] outBuffer
* returns a pointer to the original buffer
* \param[out] outLength
* returns the number of bytes of encoded data in the outBuffer
*/
void
Log::Encoder::swapBuffer(char *inBuffer, size_t inSize, char **outBuffer,
size_t *outLength, size_t *outSize)
{
char *ret = backing_buffer;
size_t size = writePos - backing_buffer;
size_t originalSize = endOfBuffer - backing_buffer;
backing_buffer = inBuffer;
writePos = inBuffer;
endOfBuffer = inBuffer + inSize;
lastBufferIdEncoded = -1;
currentExtentSize = nullptr;
if (outBuffer)
*outBuffer = ret;
if (outLength)
*outLength = size;
if (outSize)
*outSize = originalSize;
}
// Constructor for LogMessage
Log::LogMessage::LogMessage()
: metadata(nullptr)
, logId(-1)
, rdtsc(0)
, numArgs(0)
, totalCapacity(sizeof(rawArgs)/sizeof(uint64_t))
, rawArgs()
, rawArgsExtension(nullptr)
{}
// Destructor for LogMessage
Log::LogMessage::~LogMessage() {
if (rawArgsExtension != nullptr) {
free(rawArgsExtension);
rawArgsExtension = nullptr;
totalCapacity = INITIAL_SIZE;
}
}
/**
* Reserve/Allocate enough space for N parameters in the structure
*
* \param nparams
* Number of parameters to ensure space for
*/
void
Log::LogMessage::reserve(int nparams)
{
if (totalCapacity >= nparams)
return;
while (totalCapacity < nparams)
totalCapacity *= 2;
size_t newSize = sizeof(uint64_t)*(totalCapacity - INITIAL_SIZE);
uint64_t *newAllocation = static_cast<uint64_t*>(malloc(newSize));
if (newAllocation == nullptr) {
fprintf(stderr, "Could not allocate memory to store %d log "
"arguments. Exiting...", nparams);
exit(1);
}
if (rawArgsExtension == nullptr) {
rawArgsExtension = newAllocation;
return;
}
memcpy(newAllocation,
rawArgsExtension,
sizeof(uint64_t)*(numArgs - INITIAL_SIZE));
free(rawArgsExtension);
rawArgsExtension = newAllocation;
}
/**
* Ready's the structure for a new log statement by reassigning the static
* log information. Dynamic arguments can then be push()-ed into the
* structure.
*
* \param meta
* Static log data to refer to
* \param logId
* Preprocessor assigned log id of the log message
* \param rdtsc
* Invocation time of the log message
*/
void
Log::LogMessage::reset(FormatMetadata *meta, uint32_t logId, uint64_t rdtsc)
{
this->metadata = meta;
this->rdtsc = rdtsc;
this->logId = logId;
numArgs = 0;
}
// Indicates whether the structure stores a valid log statement or not
bool Log::LogMessage::valid() {
return metadata != nullptr;
}
// Returns the number of arguments currently stored for the log.
int Log::LogMessage::getNumArgs() {
return numArgs;
}
// Returns the preprocessor-assigned log identifier for this log message
uint32_t Log::LogMessage::getLogId() {
return logId;
}
// Returns the runtime timestamp for the log invocation.
uint64_t Log::LogMessage::getTimestamp() {
return rdtsc;
}
/**
* Decoder constructor.
*
* Due to the large amount of memory needed to buffer log statements, the
* decoder is intended to be constructed once and then re-used via open().
*/
Log::Decoder::Decoder()
: filename()
, inputFd(nullptr)
, logMsgsPrinted(0)
, bufferFragment(nullptr)
, good(false)
, checkpoint()
, freeBuffers()
, fmtId2metadata()
, fmtId2fmtString()
, rawMetadata(nullptr)
, endOfRawMetadata(nullptr)
, numBufferFragmentsRead(0)
, numCheckpointsRead(0)
{
// Take advantage of virtual memory an allocate an insanely large (1GB)
// buffer to store log metadata read from the logFile. Such a large buffer
// is used so that we don't have to explicitly manage the buffer and instead
// leave it up to the virtual memory system.
rawMetadata = static_cast<char*>(malloc(1024*1024*1024));
if (rawMetadata == nullptr) {
fprintf(stderr, "Could not allocate an internal 1GB buffer to store log"
" metadata");
exit(-1);
}
endOfRawMetadata = rawMetadata;
fmtId2metadata.reserve(1000);
fmtId2fmtString.reserve(1000);
bufferFragment = allocateBufferFragment();
}
/**
* Reads the metadata necessary to decompress log messages from a log file.
* This function can be invoked incrementally to build a larger dictionary from
* smaller fragments in the file and it should only be invoked once per fragment
*
* \param fd
* File descriptor pointing to the dictionary fragment
* \param flushOldDictionary
* Removes the old dictionary entries
* \return
* true if successful, false if the dictionary was corrupt
*/
bool
Log::Decoder::readDictionary(FILE *fd, bool flushOldDictionary) {
if (!readCheckpoint(checkpoint, fd)) {
fprintf(stderr, "Error: Could not read initial checkpoint, "
"the compressed log may be corrupted.\r\n");
return false;
}
size_t bytesRead = fread(endOfRawMetadata, 1, checkpoint.newMetadataBytes,
fd);
if (bytesRead != checkpoint.newMetadataBytes) {
fprintf(stderr, "Error couldn't read metadata header in log file.\r\n");
return false;
}
if (flushOldDictionary) {
endOfRawMetadata = rawMetadata;
fmtId2metadata.clear();
fmtId2fmtString.clear();
}
// Build an index of format id to metadata
const char *start = endOfRawMetadata;
const char *newEnd = endOfRawMetadata + bytesRead;
while(endOfRawMetadata < newEnd) {
std::string fmtString;
fmtId2metadata.push_back(endOfRawMetadata);
// Skip ahead
auto *fm = reinterpret_cast<FormatMetadata*>(endOfRawMetadata);
endOfRawMetadata += sizeof(FormatMetadata) + fm->filenameLength;
for (int i = 0; i < fm->numPrintFragments
&& newEnd >= endOfRawMetadata; ++i)
{
auto *pf = reinterpret_cast<PrintFragment*>(endOfRawMetadata);
endOfRawMetadata += sizeof(PrintFragment) + pf->fragmentLength;
fmtString.append(pf->formatFragment);
}
fmtId2fmtString.push_back(fmtString);
}
if (newEnd != endOfRawMetadata) {
fprintf(stderr, "Error: Log dictionary is inconsistent; "
"expected %lu bytes, but read %lu bytes\r\n",
newEnd - start,
endOfRawMetadata - start);
return false;
}
if (fmtId2metadata.size() != checkpoint.totalMetadataEntries) {
fprintf(stderr, "Error: Missing log metadata detected; "
"expected %u messages, but only found %lu\r\n",
checkpoint.totalMetadataEntries,
fmtId2metadata.size());
return false;
}
++numCheckpointsRead;
return true;
}
/**
* Parses the <length> and <specifier> components of a printf format sub-string
* according to http://www.cplusplus.com/reference/cstdio/printf/ and returns
* a corresponding FormatType.
*
* \param length
* Length component of the printf format string
* \param specifier
* Specifier component of the printf format string
* @return
* The FormatType corresponding to the length and specifier. A value of
* MAX_FORMAT_TYPE is returned in case of error.
*/
static NanoLogInternal::Log::FormatType
getFormatType(std::string length, char specifier)
{
using namespace NanoLogInternal::Log;
// Signed Integers
if (specifier == 'd' || specifier == 'i') {
if (length.empty())
return int_t;
if (length.size() == 2) {
if (length[0] == 'h') return signed_char_t;
if (length[0] == 'l') return long_long_int_t;
}
switch(length[0]) {
case 'h': return short_int_t;
case 'l': return long_int_t;
case 'j': return intmax_t_t;
case 'z': return size_t_t;
case 't': return ptrdiff_t_t;
default : break;
}
}
// Unsigned integers
if (specifier == 'u' || specifier == 'o'
|| specifier == 'x' || specifier == 'X')
{
if (length.empty())
return unsigned_int_t;
if (length.size() == 2) {
if (length[0] == 'h') return unsigned_char_t;
if (length[0] == 'l') return unsigned_long_long_int_t;
}
switch(length[0]) {
case 'h': return unsigned_short_int_t;
case 'l': return unsigned_long_int_t;
case 'j': return uintmax_t_t;
case 'z': return size_t_t;
case 't': return ptrdiff_t_t;
default : break;
}
}
// Strings
if (specifier == 's') {
if (length.empty()) return const_char_ptr_t;
if (length[0] == 'l') return const_wchar_t_ptr_t;
}
// Pointer
if (specifier == 'p') {
if (length.empty()) return const_void_ptr_t;
}
// Floating points
if (specifier == 'f' || specifier == 'F'
|| specifier == 'e' || specifier == 'E'
|| specifier == 'g' || specifier == 'G'
|| specifier == 'a' || specifier == 'A')
{
if (length.size() == 1 && length[0] == 'L' )
return long_double_t;
else
return double_t;
}
if (specifier == 'c') {
if (length.empty()) return int_t;
if (length[0] == 'l') return wint_t_t;
}
fprintf(stderr, "Attempt to decode format specifier failed: %s%c\r\n",
length.c_str(), specifier);
return MAX_FORMAT_TYPE;
}
/**
* Generate a more efficient internal representation describing how to process
* the compressed arguments of a NANO_LOG statement given its static
* log information.
*
* The output representation would look something like a FormatMetadata with
* nested PrintFragments. This representation can then be interpreted by the
* state machine in decompressNextLogStatement to decompress the log statements.
*
* \param[in/out] microCode
* Buffer to store the generated internal representation
* \param formatString
* Format string of the NANO_LOG statement
* \param filename
* File associated with the log invocation site
* \param linenum
* Line number within filename associated with the log invocation site
* \param severity
* LogLevel severity associated with the log invocation site
* \return
* true indicates success; false indicates malformed printf format string
*/
bool
Log::Decoder::createMicroCode(char **microCode,
const char *formatString,
const char *filename,
uint32_t linenum,
uint8_t severity)
{
using namespace NanoLogInternal::Log;
size_t formatStringLength = strlen(formatString) + 1; // +1 for NULL
char *microCodeStartingPos = *microCode;
FormatMetadata *fm = reinterpret_cast<FormatMetadata*>(*microCode);
*microCode += sizeof(FormatMetadata);
fm->logLevel = severity;
fm->lineNumber = linenum;
fm->filenameLength = static_cast<uint16_t>(strlen(filename) + 1);
*microCode = stpcpy(*microCode, filename) + 1;
fm->numNibbles = 0;
fm->numPrintFragments = 0;
std::regex regex("^%"
"([-+ #0]+)?" // Flags (Position 1)
"([\\d]+|\\*)?" // Width (Position 2)
"(\\.(\\d+|\\*))?"// Precision (Position 4; 3 includes '.')
"(hh|h|l|ll|j|z|Z|t|L)?" // Length (Position 5)
"([diuoxXfFeEgGaAcspn])"// Specifier (Position 6)
);
size_t i = 0;
std::cmatch match;
int consecutivePercents = 0;
size_t startOfNextFragment = 0;
PrintFragment *pf = nullptr;
// The key idea here is to split up the format string in to fragments (i.e.
// PrintFragments) such that there is at most one specifier per fragment.
// This then allows the decompressor later to consume one argument at a
// time and print the fragment (vs. buffering all the arguments first).
while (i < formatStringLength) {
char c = formatString[i];
// Skip the next character if there's an escape
if (c == '\\') {
i += 2;
continue;
}
if (c != '%') {
++i;
consecutivePercents = 0;
continue;
}
// If there's an even number of '%'s, then it's a comment
if (++consecutivePercents % 2 == 0
|| !std::regex_search(formatString + i, match, regex))
{
++i;
continue;
}
// Advance the pointer to the end of the specifier & reset the % counter
consecutivePercents = 0;
i += match.length();
// At this point we found a match, let's start analyzing it
pf = reinterpret_cast<PrintFragment*>(*microCode);
*microCode += sizeof(PrintFragment);
std::string width = match[2].str();
std::string precision = match[4].str();
std::string length = match[5].str();
char specifier = match[6].str()[0];
FormatType type = getFormatType(length, specifier);
if (type == MAX_FORMAT_TYPE) {
fprintf(stderr, "Error: Couldn't process this: %s\r\n",
match.str().c_str());
*microCode = microCodeStartingPos;
return false;
}
pf->argType = 0x1F & type;
pf->hasDynamicWidth = (width.empty()) ? false : width[0] == '*';
pf->hasDynamicPrecision = (precision.empty()) ? false
: precision[0] == '*';
// Tricky tricky: We null-terminate the fragment by copying 1
// extra byte and then setting it to NULL
pf->fragmentLength = static_cast<uint16_t>(i - startOfNextFragment + 1);
memcpy(*microCode,
formatString + startOfNextFragment,
pf->fragmentLength);
*microCode += pf->fragmentLength;
*(*microCode - 1) = '\0';
// Non-strings and dynamic widths need nibbles!
if (specifier != 's')
++fm->numNibbles;
if (pf->hasDynamicWidth)
++fm->numNibbles;
if (pf->hasDynamicPrecision)
++fm->numNibbles;
#ifdef ENABLE_DEBUG_PRINTING
printf("Fragment %d: %s\r\n", fm->numPrintFragments,pf->formatFragment);
printf("\t\ttype: %u, dWidth: %u, dPrecision: %u, length: %u\r\n",
pf->argType,
pf->hasDynamicWidth,
pf->hasDynamicPrecision,
pf->fragmentLength);
#endif
startOfNextFragment = i;
++fm->numPrintFragments;
}
// If we didn't encounter any specifiers, make one for a basic string
if (pf == nullptr) {
pf = reinterpret_cast<PrintFragment*>(*microCode);
*microCode += sizeof(PrintFragment);
fm->numPrintFragments = 1;
pf->argType = FormatType::NONE;
pf->hasDynamicWidth = pf->hasDynamicPrecision = false;
pf->fragmentLength = downCast<uint16_t>(formatStringLength);
memcpy(*microCode, formatString, formatStringLength);
*microCode += formatStringLength;
} else {
// Extend the last fragment to include the rest of the string
size_t endingLength = formatStringLength - startOfNextFragment;
memcpy(pf->formatFragment + pf->fragmentLength - 1, // -1 to erase \0
formatString + startOfNextFragment,
endingLength);
pf->fragmentLength = downCast<uint16_t>(pf->fragmentLength - 1
+ endingLength);
*microCode += endingLength;
}
#ifdef ENABLE_DEBUG_PRINTING
printf("Fragment %d: %s\r\n", fm->numPrintFragments, pf->formatFragment);
printf("\t\ttype: %u, dWidth: %u, dPrecision: %u, length: %u\r\n",
pf->argType,
pf->hasDynamicWidth,
pf->hasDynamicPrecision,
pf->fragmentLength);
#endif
return true;
}
/**
* Reads a partial dictionary from the log file and adds it to the global
* mapping of log identifiers to static log information.
*
* \param fd
* File descriptor to read the mapping from
* \return
* true indicates success; false indicates error
*/
bool
Log::Decoder::readDictionaryFragment(FILE *fd) {
// These buffers start us off with some statically allocated space.
// Should we need more, we will malloc it.
size_t bufferSize = 10*1024;
char filenameBuffer[bufferSize];
char formatBuffer[bufferSize];
bool newBuffersAllocated = false;
char *filename = filenameBuffer;
char *format = formatBuffer;