-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathEventHeaderDynamic.h
1707 lines (1473 loc) · 68.1 KB
/
EventHeaderDynamic.h
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) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/*
C++ API for runtime-specified eventheader-encoded Linux Tracepoints via
libtracepoint
This API is intended for use when the set of events to be logged is not known
at compile-time, e.g. when implementing a middle-layer for a high-level tracing
API such as OpenTelemetry. This API should not be directly used by developers
instrumenting their own code because it is less user-friendly and less efficient
than alternatives like TraceLoggingProvider.h.
Basic usage of this API:
- Create a Provider object with a name and an optional group.
- Use the Provider to get the EventSet with the level and keyword you need.
- As an optimization, use Enabled(eventSet) to determine whether anybody
is listening for a particular provider + event level + event keyword
combination. If nobody is listening, you should skip the remaining steps
because there is no need to build and write an event that nobody will
receive.
- Use an EventBuilder to build and write the event:
- Create an EventBuilder.
- Call eventBuilder.Reset(...) to set the event name and to set the event
tag (if any).
- Call eventBuilder.AddValue(...) and similar methods to add fields to the
event or to configure the event's other attributes (e.g. opcode, id,
version).
- Call eventBuilder.Write(eventSet, ...) to send the event to the system
with the eventSet's provider, level, and keyword.
Notes:
- EventBuilder is reusable. If you need to generate several events, you may
get a small performance benefit by reusing one EventBuilder rather than
using a new EventBuilder for each event.
- Events are limited in size (event size = headers + metadata + data). The
kernel will ignore any event that is larger than 64KB.
- All event sets for a provider will become disabled when the provider is
destroyed or when you call provider.Unregister().
- The Provider object is not thread-safe, but the EventSet object is
thread-safe. Possible strategies for multi-threaded programs might include:
- Have a reader-writer lock for the provider. Take an exclusive lock for
non-const operations like RegisterSet() and Unregister(). Take a shared
lock for other provider operations like FindSet().
- Create the provider and do all of the necessary RegisterSet() calls
before any other threads start using it. Then you can call the const
methods like FindSet() as needed on any thread without any lock as long
as nobody is calling any non-const methods.
- Use your own thread-safe data structure to keep track of all of the
EventSets you need. Take a lock if you ever need to register a new set.
- Each event set maps to one tracepoint name, e.g. if the provider name is
"MyCompany_MyComponent", level is verbose (5), and keyword is 0x1f, the
event set will correspond to a tracepont named
"user_events:MyCompany_MyComponent_L5K1f".
- Collect events to a file using a tool such as "perf", e.g.
"perf record -k monotonic -e user_events:MyCompany_MyComponent_L5K1f".
- Decode events using a tool such as "perf-decode" (from the tools in the
libeventheader-decode-cpp library).
*/
#pragma once
#ifndef _included_EventHeaderDynamic_h
#define _included_EventHeaderDynamic_h 1
#if __cplusplus < 201703L && (!defined(_MSVC_LANG) || _MSVC_LANG < 201703L)
#error EventHeaderDynamic.h requires C++17 or later.
#endif
#include "eventheader-tracepoint.h"
#include <assert.h>
#include <string.h>
#include <memory>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <vector>
#ifdef _WIN32
#include <sal.h>
#endif
#ifndef _In_opt_
#define _In_opt_
#endif
#ifndef _In_reads_bytes_opt_
#define _In_reads_bytes_opt_(size)
#endif
#ifndef _In_reads_
#define _In_reads_(count)
#endif
#ifndef _Success_
#define _Success_(condition)
#endif
#ifndef _Outptr_result_bytebuffer_
#define _Outptr_result_bytebuffer_(size)
#endif
#ifndef _Out_opt_
#define _Out_opt_
#endif
namespace ehd
{
/*
Represents a group of events with the same provider, level, and keyword.
Each EventSet corresponds to one tracepoint name. For example, the EventSet
with provider name "MyCompany_MyComponent", level verbose (5), and keyword
0x1f would correspond to a tracepoint named
"user_events:MyCompany_MyComponent_L5K1f".
Get an EventSet by calling provider.RegisterSet(level, keyword) or
provider.FindSet(level, keyword).
Use an EventSet by calling Enabled(eventSet) or
eventBuilder.Write(eventSet, ...);
*/
class EventSet
{
friend class Provider; // Forward declaration
friend class EventBuilder; // Forward declaration
tracepoint_state m_tracepointState;
uint8_t m_level;
int m_errno;
public:
EventSet(EventSet const&) = delete;
void operator=(EventSet const&) = delete;
/*
Creates an inactive (unregistered) EventSet. The returned event set's
Enabled() method will always return false, and any attempt to write
to this event set will have no effect (safe no-op).
This method may be used to create a placeholder event set. Active
(registered) event sets are created using provider.RegisterSet().
*/
constexpr
EventSet() noexcept
: m_tracepointState(TRACEPOINT_STATE_INIT)
, m_level()
, m_errno(22) // EINVAL
{
return;
}
/*
Returns true if any logging session is listening for events with the
provider, level, and keyword associated with this event set.
For shared_ptr<EventSet> where the eventSetPtr might be NULL, consider
using Enabled(eventSetPtr), which is equivalent to
(eventSetPtr != NULL && eventSetPtr->Enabled()).
*/
bool
Enabled() const noexcept
{
return TRACEPOINT_ENABLED(&m_tracepointState);
}
/*
For diagnostics/debugging (usually ignored in production).
Returns 0 if this event set was successfully registered, or a nonzero
error code if ioctl(user_events_data, DIAG_IOCSREG, ...) returned an
error.
*/
int
Errno() const noexcept
{
return m_errno;
}
};
/*
Represents a named event provider. Use a provider to manage the EventSets.
- Call provider.RegisterSet(level, keyword) to get a shared_ptr<EventSet>
that can be used to write events with the corresponding
provider + level + keyword.
- Call provider.FindSet(level, keyword) to get a shared_ptr<EventSet> to
an EventSet that was previously registered.
- Call provider.Unregister() if you want to disconnect the provider before
it goes out of scope.
Note that Provider is not thread-safe, but the shared_ptr<EventSet> objects
returned by RegisterSet() and FindSet() are thread-safe. Possible ways to
safely use a provider in a multi-threaded program:
- Have a reader-writer lock for the provider. Take an exclusive lock for
non-const operations like RegisterSet() and Unregister(). Take a shared
lock for other provider operations like FindSet().
- Create the provider and do all of the necessary RegisterSet() calls
before any other threads start using it. Then you can call the const
methods like FindSet() on any thread as needed without any lock as long
as nobody is calling any non-const methods.
- Use your own thread-safe data structure to keep track of all of the
EventSets you need. Take a lock if you ever need to register a new set.
*/
class Provider
{
static auto constexpr NamesMax = EVENTHEADER_NAME_MAX - sizeof("_LffKffffffffffffffffG");
struct EventKey
{
uint64_t Keyword;
uint8_t Level; // Comes after keyword so that there is no padding between them.
};
struct EventKeyOps
{
// hash
size_t
operator()(EventKey const& a) const noexcept
{
// FNV-1a
constexpr auto Prime = sizeof(size_t) == 8
? static_cast<size_t>(0x00000100000001B3)
: static_cast<size_t>(0x01000193);
auto h = sizeof(size_t) == 8
? static_cast<size_t>(0xcbf29ce484222325)
: static_cast<size_t>(0x811c9dc5);
auto const p = reinterpret_cast<uint8_t const*>(&a);
assert(&a.Level - p == 8);
for (unsigned i = 0; i != 9; i += 1)
{
h = (h ^ p[i]) * Prime;
}
return h;
}
// equals
bool
operator()(EventKey const& a, EventKey const& b) const noexcept
{
return 0 == memcmp(&a, &b, 9);
}
};
using EventSetMap = std::unordered_map<EventKey, std::shared_ptr<EventSet const>, EventKeyOps, EventKeyOps>;
EventSetMap m_eventSets;
tracepoint_provider_state m_providerState;
eventheader_provider m_provider;
int m_errno;
char m_nameOptionsBuffer[NamesMax + 3]; // 3 = provider name's NUL + 'G' + option's NUL.
public:
Provider(Provider const&) = delete;
void operator=(Provider const&) = delete;
~Provider()
{
eventheader_close_provider(&m_provider);
}
/*
Creates a new provider.
- providerName is the name to use for this provider. It must be less than 234
chars and must not contain '\0', ' ', or ':'. For best compatibility with
trace processing components, it should contain only ASCII letters, digits,
and '_'. It should be short, human-readable, and unique enough to not
conflict with names of other providers. The provider name will typically
include a company name and a component name, e.g. "MyCompany_MyComponent".
- groupName can usually be "". If the provider needs to join a provider group,
specify the group name, which must contain only ASCII lowercase letters and
digits. The total length of the provider name + the group name must be less
than 234.
Use RegisterSet() to register event sets and add them to the per-provider list
of event sets. Use FindSet() to find a set that is already in the list.
Use EventBuilder to create events, then write them to an event set.
Requires: strlen(providerName) + strlen(groupName) < 234.
Requires: providerName does not contain '\0', ' ', or ':'.
Requires: groupName contains only ASCII lowercase letters and digits.
*/
explicit
Provider(
std::string_view providerName,
std::string_view groupName = std::string_view()) noexcept
: m_eventSets()
, m_providerState(TRACEPOINT_PROVIDER_STATE_INIT)
, m_provider()
, m_errno()
{
// Precondition violation: providerName must not contain these chars.
assert(providerName.npos == providerName.find('\0'));
assert(providerName.npos == providerName.find(' '));
assert(providerName.npos == providerName.find(':'));
using namespace std::string_view_literals;
constexpr size_t NamesMax = EVENTHEADER_NAME_MAX - "_LffKffffffffffffffffG"sv.size();
// Precondition violation: providerName must be less than 234 chars.
assert(providerName.size() < NamesMax);
auto const cchProviderName = providerName.size() < NamesMax
? providerName.size()
: NamesMax - 1;
m_provider.state = &m_providerState;
m_provider.name = m_nameOptionsBuffer;
m_provider.options = m_nameOptionsBuffer + cchProviderName + 1;
size_t cchGroupName;
for (cchGroupName = 0; groupName.size() != cchGroupName; cchGroupName += 1)
{
if (cchGroupName == NamesMax - cchProviderName - 1)
{
assert(false); // Precondition violation: providerName + groupName too long.
break; // In release builds, stop here.
}
auto const ch = groupName[cchGroupName];
if ((ch < '0' || '9' < ch) && (ch < 'a' || 'z' < ch))
{
assert(false); // Precondition violation: groupName contains invalid chars.
break; // In release builds, stop here.
}
}
auto pStrings = m_nameOptionsBuffer;
// Create provider name string.
assert(pStrings == m_provider.name);
memcpy(pStrings, providerName.data(), cchProviderName);
pStrings += cchProviderName;
*pStrings = '\0';
pStrings += 1;
// Create options string.
assert(pStrings == m_provider.options);
if (cchGroupName != 0)
{
*pStrings = 'G';
pStrings += 1;
memcpy(pStrings, groupName.data(), cchGroupName);
pStrings += cchGroupName;
}
*pStrings = '\0';
pStrings += 1;
assert(pStrings <= m_nameOptionsBuffer + sizeof(m_nameOptionsBuffer));
m_errno = eventheader_open_provider(&m_provider);
}
/*
Returns this provider's name.
*/
std::string_view
Name() const noexcept
{
assert(m_provider.name < m_provider.options);
assert(m_provider.options[-1] == 0);
return std::string_view(m_provider.name, m_provider.options - m_provider.name - 1);
}
/*
Returns the options string, e.g. "" or "Gmygroup".
*/
std::string_view
Options() const noexcept
{
return m_provider.options;
}
/*
For diagnostics/debugging (usually ignored in production).
Returns 0 if this provider was successfully registered, or a nonzero
errno code if eventheader_open_provider() failed.
*/
int
Errno() const noexcept
{
return m_errno;
}
/*
If this provider is not registered, does nothing and returns 0.
Otherwise, unregisters all event sets that were registered by this provider
and clears the list of already-created event sets.
Use provider.Unregister() if you want to unregister the provider before it goes
out of scope. The provider automatically unregisters when it is destroyed so
most users do not need to call Unregister() directly.
*/
void
Unregister() noexcept
{
eventheader_close_provider(&m_provider);
m_eventSets.clear();
}
/*
If an event set with the specified level and keyword is in the list of
already-created sets, returns it. Otherwise, returns nullptr.
*/
std::shared_ptr<EventSet const>
FindSet(event_level level, uint64_t keyword) const noexcept
{
EventKey const k = { keyword, static_cast<uint8_t>(level) };
auto const it = m_eventSets.find(k);
return it == m_eventSets.end() ? std::shared_ptr<EventSet const>() : it->second;
}
/*
If an event set with the specified level and keyword is in the list of
already-created sets, returns it. Otherwise, creates a new event set, adds it to
the list of already-created sets, attempts to register it, and returns the new
event set. If registration fails, the new event set will have a non-zero errno
and will never be enabled.
In case of out-of-memory, returns nullptr.
*/
std::shared_ptr<EventSet const>
RegisterSet(event_level level, uint64_t keyword) noexcept
{
std::shared_ptr<EventSet const> result;
EventKey const k = { keyword, static_cast<uint8_t>(level) };
std::pair<EventSetMap::iterator, bool> emplace_result;
try
{
emplace_result = m_eventSets.emplace(k, std::shared_ptr<EventSet const>());
}
catch (...)
{
return result; // nullptr.
}
if (!emplace_result.second)
{
result = emplace_result.first->second;
}
else try
{
auto created = std::make_shared<EventSet>();
created->m_level = static_cast<uint8_t>(level);
if (m_errno)
{
created->m_errno = m_errno; // Propagate error from eventheader_open_provider.
}
else
{
eventheader_tracepoint tp = {
&created->m_tracepointState,
nullptr,
{ 0, 0, 0, 0, 0, static_cast<uint8_t>(level) },
keyword };
created->m_errno = eventheader_connect(&tp, &m_provider);
}
emplace_result.first->second = std::move(created);
result = emplace_result.first->second;
}
catch (...)
{
m_eventSets.erase(k);
}
return result;
}
/*
For testing purposes: Creates an inactive (unregistered) event set.
If an event set with the specified level and keyword is in the list of
already-created sets, returns it. Otherwise, creates a new **unregistered**
event set, adds it to the list of already-created sets, and returns the new
event set.
In case of out-of-memory, returns nullptr.
*/
std::shared_ptr<EventSet const>
CreateUnregistered(event_level level, uint64_t keyword, bool enabled = false) noexcept
{
std::shared_ptr<EventSet const> result;
EventKey const k = { keyword, static_cast<uint8_t>(level) };
std::pair<EventSetMap::iterator, bool> emplace_result;
try
{
emplace_result = m_eventSets.emplace(k, std::shared_ptr<EventSet const>());
}
catch (...)
{
return result; // nullptr.
}
if (!emplace_result.second)
{
result = emplace_result.first->second;
}
else try
{
auto created = std::make_shared<EventSet>();
created->m_level = static_cast<uint8_t>(level);
created->m_errno = 0;
created->m_tracepointState.status_word = enabled;
emplace_result.first->second = std::move(created);
result = emplace_result.first->second;
}
catch (...)
{
m_eventSets.erase(k);
}
return result;
}
};
/*
Stores event attributes: name, fields, id, version, tag, opcode.
Usage:
- Create a provider.
- Use the provider to get an eventSet.
- If the eventSet is not enabled, skip the remaining steps.
- Create an eventBuilder.
- Call eventBuilder.Reset(name, ...) to start building an event.
- Call other methods on eventBuilder to set attributes or add fields.
- Call eventBuilder.Write(eventSet, ...) to write the event.
*/
class EventBuilder
{
// Optimization: Use vector for capacity management but not size management.
// Otherwise, vector repeatedly zeroes memory that we just overwrite.
class Buffer
{
uint8_t* m_next;
std::vector<uint8_t> m_data;
public:
Buffer() noexcept
: m_next()
, m_data()
{
m_next = m_data.data();
}
size_t
size() const noexcept
{
return m_next - m_data.data();
}
uint8_t const*
data() const noexcept
{
return m_data.data();
}
uint8_t*
data() noexcept
{
return m_data.data();
}
void
clear() noexcept
{
m_next = m_data.data();
}
void
advance(size_t cbUsed) noexcept
{
assert(cbUsed <= static_cast<size_t>(m_data.data() + m_data.size() - m_next));
m_next += cbUsed;
}
_Success_(return) bool
ensure_space_for(size_t cbRequired, _Outptr_result_bytebuffer_(cbRequired) uint8_t** ppBuffer) noexcept
{
// Keep small so it's likely to be inlined.
*ppBuffer = m_next;
return cbRequired <= static_cast<size_t>(m_data.data() + m_data.size() - m_next)
|| GrowToProvideSpaceFor(cbRequired, ppBuffer);
}
private:
_Success_(return) bool
GrowToProvideSpaceFor(size_t cbRequired, _Outptr_result_bytebuffer_(cbRequired) uint8_t** ppBuffer) noexcept
{
size_t const oldSize = m_next - m_data.data();
assert(oldSize <= m_data.size());
size_t const minSize = oldSize + cbRequired;
if (minSize < cbRequired)
{
// integer overflow
}
else try
{
m_data.reserve(minSize);
m_data.resize(m_data.capacity());
assert(minSize <= m_data.size());
m_next = m_data.data() + oldSize;
*ppBuffer = m_next;
return true;
}
catch (...)
{
// length error or out-of-memory.
}
// integer overflow, length error, or out-of-memory.
*ppBuffer = nullptr;
return false;
}
};
template<unsigned Size>
struct TypeInfo
{
static event_field_encoding const ValueEncoding =
Size == 1 ? event_field_encoding_value8
: Size == 2 ? event_field_encoding_value16
: Size == 4 ? event_field_encoding_value32
: Size == 8 ? event_field_encoding_value64
: Size == 16 ? event_field_encoding_value128
: event_field_encoding_invalid;
static event_field_encoding const StringEncoding =
Size == 1 ? event_field_encoding_string_length16_char8
: Size == 2 ? event_field_encoding_string_length16_char16
: Size == 4 ? event_field_encoding_string_length16_char32
: event_field_encoding_invalid;
static event_field_encoding const ZStringEncoding =
Size == 1 ? event_field_encoding_zstring_char8
: Size == 2 ? event_field_encoding_zstring_char16
: Size == 4 ? event_field_encoding_zstring_char32
: event_field_encoding_invalid;
static event_field_encoding const BinaryEncoding =
Size == 1 ? event_field_encoding_binary_length16_char8
: event_field_encoding_invalid;
};
/*
Detects whether the specified value type has a supported size
(1, 2, 4, 8, or 16) and is trivially-copyable. If so, supplies the
ValueEncoding (value8, value16, value32, value64, value128).
*/
template<class ValTy>
struct ValueEnabled
: std::enable_if<
std::is_trivially_copyable<ValTy>::value &&
TypeInfo<sizeof(ValTy)>::ValueEncoding != event_field_encoding_invalid,
EventBuilder&>
, TypeInfo<sizeof(ValTy)>
{};
/*
Detects whether the specified char type has a supported size
(1, 2, or 4) and is trivially-copyable. If so, supplies the StringEncoding
and ZStringEncoding (char8, char16, char32).
*/
template<class CharTy, bool ExtraCondition = true>
struct StringEnabled
: std::enable_if<
ExtraCondition &&
std::is_trivially_copyable<CharTy>::value &&
TypeInfo<sizeof(CharTy)>::StringEncoding != event_field_encoding_invalid,
EventBuilder&>
, TypeInfo<sizeof(CharTy)>
{};
/*
Detects whether the specified char type has a supported size
(1) and is trivially-copyable. If so, supplies the BinaryEncoding
(char8).
*/
template<class CharTy, bool ExtraCondition = true>
struct BinaryEnabled
: std::enable_if<
ExtraCondition &&
std::is_trivially_copyable<CharTy>::value &&
TypeInfo<sizeof(CharTy)>::BinaryEncoding != event_field_encoding_invalid,
EventBuilder&>
, TypeInfo<sizeof(CharTy)>
{};
Buffer m_meta;
Buffer m_data;
bool m_error;
uint8_t m_version;
uint16_t m_id;
uint16_t m_tag;
uint8_t m_opcode;
public:
/*
Returns a new event builder with specified initial buffer capacities.
Buffers will automatically grow as needed.
Call Reset() to start building a new event.
*/
explicit
EventBuilder(uint16_t metaCapacity = 256, uint16_t dataCapacity = 256) noexcept
: m_meta()
, m_data()
, m_error(true)
, m_version()
, m_id()
, m_tag()
, m_opcode()
{
uint8_t* pIgnored;
m_meta.ensure_space_for(metaCapacity, &pIgnored);
m_data.ensure_space_for(dataCapacity, &pIgnored);
}
/*
Clears the previous event (if any) from the builder and starts building a new
event.
- name is the event name. It should be short and unique. It must not contain '\0'.
- tag is a 16-bit integer that will be recorded in the event and can be
used for any provider-defined purpose. Use 0 if you are not using event tags.
*/
EventBuilder&
Reset(std::string_view name, uint16_t tag = 0) noexcept
{
// Precondition violation: name must not contain '\0'.
assert(name.find('\0') == name.npos);
m_meta.clear();
m_data.clear();
m_error = false;
m_version = 0;
m_id = 0;
m_tag = tag;
m_opcode = event_opcode_info;
uint8_t* pMeta;
if (!m_meta.ensure_space_for(name.size() + 1, &pMeta))
{
m_error = true;
}
else
{
memcpy(pMeta, name.data(), name.size());
pMeta[name.size()] = '\0';
m_meta.advance(name.size() + 1);
}
return *this;
}
/*
Sends the finished event to the kernel with the provider, event level, and event
keyword of the specified event set.
- eventSet should be a registered and enabled event set. Calling Write on an
unregistered or disabled event set is a safe no-op (usually returns 0 in this
case, though it may return ERANGE if the event is too large).
- activityId contains a pointer to the 16-byte activity id to be assigned to the
event, or nullptr if the event is not part of an activity. (An activity is a
group of related events that all have the same activity id, started by an event
with event_opcode_activity_start and ended by an event with
event_opcode_activity_stop.)
- relatedId contains a pointer to the 16-byte related activity id (parent activity)
to be used for an activity-start event, or nullptr if the event is not an
activity-start event or does not have a parent activity. If activityId is nullptr,
this must also be nullptr.
Returns 0 for success. Returns a nonzero errno value for failure. The return
value is for diagnostic/debugging purposes only and should generally be ignored
in retail builds. Returns EBADF (9) if tracepoint is unregistered or disabled.
Returns ENOMEM (12) if out of memory. Returns ERANGE (34) if the event (headers +
metadata + data) is greater than 64KB. Returns other errors as reported by writev.
*/
int
Write(
EventSet const& eventSet,
_In_reads_bytes_opt_(16) void const* activityId = nullptr,
_In_reads_bytes_opt_(16) void const* relatedId = nullptr) const noexcept
{
assert(relatedId == nullptr || activityId != nullptr);
if (m_error)
{
return 12; // ENOMEM
}
else if (m_meta.size() + m_data.size() > 65535 - (52 + 16))
{
return 34; // ERANGE
}
else
{
eventheader_extension metadataExt = {};
metadataExt.size = static_cast<uint16_t>(m_meta.size());
metadataExt.kind = eventheader_extension_kind_metadata;
iovec dataVecs[EVENTHEADER_PREFIX_DATAVEC_COUNT_NO_METADATA + 3];
dataVecs[EVENTHEADER_PREFIX_DATAVEC_COUNT_NO_METADATA + 0] = { &metadataExt, sizeof(metadataExt) };
dataVecs[EVENTHEADER_PREFIX_DATAVEC_COUNT_NO_METADATA + 1] = { (void*)m_meta.data(), m_meta.size() };
dataVecs[EVENTHEADER_PREFIX_DATAVEC_COUNT_NO_METADATA + 2] = { (void*)m_data.data(), m_data.size() };
eventheader_tracepoint tp = {};
tp.state = const_cast<tracepoint_state*>(&eventSet.m_tracepointState);
tp.header.flags = eventheader_flag_default_with_extension;
tp.header.version = m_version;
tp.header.id = m_id;
tp.header.tag = m_tag;
tp.header.opcode = m_opcode;
tp.header.level = eventSet.m_level;
return eventheader_write(
&tp,
activityId,
relatedId,
sizeof(dataVecs) / sizeof(dataVecs[0]),
dataVecs);
}
}
/*
Sets the manually-assigned id and version of the event to be generated
by this builder. Most events will use id = 0, version = 0, indicating
that the event does not have a manually-assigned id and is identified
by event name rather than by event id.
Call this with a nonzero value for id if the event has a
manually-assigned (durable) unique id.
When the id is first assigned, use version 0. Increment version each
time the event schema changes (each time you make a change to the
event name, field names, field types, etc.).
*/
EventBuilder&
IdVersion(uint16_t id, uint8_t version) noexcept
{
m_id = id;
m_version = version;
return *this;
}
/*
Sets the opcode of the event, indicating special semantics to be used
by event decoders, e.g. activity-start or activity-stop. Most events
do not have special semantics so most events use the default opcode,
info (0).
*/
EventBuilder&
Opcode(event_opcode opcode) noexcept
{
m_opcode = static_cast<uint8_t>(opcode);
return *this;
}
/*
Adds a field containing the specified number of sub-fields.
A struct is a way to logically group a number of fields. To add a struct to
an event, call builder.AddStruct("StructName", structFieldCount).
Then add structFieldCount more fields and they will be considered to be
members of the struct.
- fieldName should be a short and distinct string that describes the field.
- structFieldCount specifies the number of subsequent fields that will be
considered to be part of this struct field. This must be in the range 1 to
127. Empty structs (structs that contain no fields) are not permitted.
- fieldTag is a 16-bit integer that will be recorded in the field and can be
used for any provider-defined purpose. Use 0 if you are not using field tags.
- pFieldCountBookmark (advanced): If you don't know how many fields will be in
the struct ahead of time, pass 1 for structFieldCount and pass the address of
a size_t variable to receive a bookmark. After you have added all of the fields
you can then use the bookmark to set the actual structFieldCount value. Note
that structFieldCount still cannot be 0 or larger than 127. Use nullptr if
you are passing the actual field count in the structFieldCount parameter.
Structs can nest. Each nested struct and its fields count as 1 field for the
parent struct.
*/
EventBuilder&
AddStruct(
std::string_view fieldName,
uint8_t structFieldCount,
uint16_t fieldTag = 0,
_Out_opt_ size_t* pFieldCountBookmark = nullptr) noexcept
{
uint8_t maskedFieldCount = structFieldCount & event_field_format_value_mask;
assert(structFieldCount == maskedFieldCount); // Precondition: structFieldCount must be less than 128.
size_t fieldCountBookmark;
if (structFieldCount == 0)
{
assert(structFieldCount != 0); // Precondition: structFieldCount must not be 0.
fieldCountBookmark = -1;
}
else
{
fieldCountBookmark = RawAddMeta(fieldName, event_field_encoding_struct, maskedFieldCount, fieldTag);
}
if (pFieldCountBookmark)
{
*pFieldCountBookmark = fieldCountBookmark;
}
return *this;
}
/*
Advanced: Resets the number of logical fields in a structure.
Requires:
- fieldCountBookmark is a bookmark value returned by AddStruct, and you
haven't called Reset since that bookmark was returned.
- structFieldCount is a value from 1 to 127. (Must not be 0. Must be less
than 128.)
If the final number of fields of a structure is not known at the time
you need to start the structure, you can follow this procedure:
- Create a size_t bookmark variable.
- In the AddStruct call, pass 1 as the number of fields, and pass &bookmark
as the pFieldCountBookmark parameter.
- After you know the actual number of fields, call
SetStructFieldCount(bookmark, fieldCount).
*/
EventBuilder&
SetStructFieldCount(size_t fieldCountBookmark, uint8_t structFieldCount) noexcept
{
uint8_t maskedFieldCount = structFieldCount & event_field_format_value_mask;
assert(structFieldCount == maskedFieldCount); // Precondition: structFieldCount must be less than 128.
if (structFieldCount == 0)
{
assert(structFieldCount != 0); // Precondition: structFieldCount must not be 0.
}
else if (fieldCountBookmark < m_meta.size())
{
auto const pEncoding = m_meta.data() + fieldCountBookmark;
*pEncoding = (*pEncoding & 0x80) | maskedFieldCount;
}
else
{
// Precondition: fieldCountBookmark must be a valid bookmark from AddStruct.
assert(fieldCountBookmark == static_cast<size_t>(-1));
}
return *this;
}
/*
Adds a field containing a simple value.
- fieldName should be a short and distinct string that describes the field.
- fieldValue provides the data for the field. Note that the data is treated
as raw bytes, i.e. there will be no error, warning, or data conversion if the
type of the fieldValue parameter conflicts with the format parameter. See below
for the types accepted for this parameter.
- format indicates how the decoder should interpret the field data. For example,
if the field value is int8_t or int32_t, you would likely set format to
event_field_format_signed_int, and if the field value is float or double, you
would likely set format to event_field_format_float.
- fieldTag is a 16-bit integer that will be recorded in the field and can be
used for any provider-defined purpose. Use 0 if you are not using field tags.
Types:
- If fieldValue is a 1-byte type (e.g. char, bool), the field will be encoded as
value8. For 1-byte types, if format is default, the field will be formatted as
unsigned_int. Usable formats for 1-byte types include: unsigned_int, signed_int,
hex_int, boolean, hex_bytes, string8.
- If fieldValue is a 2-byte type (e.g. short), the field will be encoded as
value16. For 2-byte types, if format is default, the field will be formatted as
unsigned_int. Usable formats for 2-byte types include: unsigned_int, signed_int,
hex_int, boolean, hex_bytes, string_utf, port.
- If fieldValue is a 4-byte type (e.g. int, float), the field will be encoded as
value32. For 4-byte types, if format is default, the field will be formatted as
unsigned_int. Usable formats for 4-byte types include: unsigned_int, signed_int,
hex_int, errno, pid, time, boolean, float, hex_bytes, string_utf, ipv4.
- If fieldValue is an 8-byte type (e.g. long long, double), the field will be