forked from dotnet/coreclr
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutil.h
More file actions
3211 lines (2661 loc) · 94.8 KB
/
util.h
File metadata and controls
3211 lines (2661 loc) · 94.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ==++==
//
//
// ==--==
#ifndef __util_h__
#define __util_h__
#define LIMITED_METHOD_CONTRACT
// So we can use the PAL_TRY_NAKED family of macros without dependencies on utilcode.
inline void RestoreSOToleranceState() {}
#include <cor.h>
#include <corsym.h>
#include <clrdata.h>
#include <palclr.h>
#include <metahost.h>
#include <new>
#if !defined(FEATURE_PAL)
#include <dia2.h>
#endif
#ifdef STRIKE
#if defined(_MSC_VER)
#pragma warning(disable:4200)
#pragma warning(default:4200)
#endif
#include "data.h"
#endif //STRIKE
#include "cordebug.h"
#include "static_assert.h"
typedef LPCSTR LPCUTF8;
typedef LPSTR LPUTF8;
DECLARE_HANDLE(OBJECTHANDLE);
struct IMDInternalImport;
#if defined(_TARGET_WIN64_)
#define WIN64_8SPACES ""
#define WIN86_8SPACES " "
#define POINTERSIZE "16"
#define POINTERSIZE_HEX 16
#define POINTERSIZE_BYTES 8
#define POINTERSIZE_TYPE "I64"
#else
#define WIN64_8SPACES " "
#define WIN86_8SPACES ""
#define POINTERSIZE "8"
#define POINTERSIZE_HEX 8
#define POINTERSIZE_BYTES 4
#define POINTERSIZE_TYPE "I32"
#endif
#ifndef TARGET_POINTER_SIZE
#define TARGET_POINTER_SIZE POINTERSIZE_BYTES
#endif // TARGET_POINTER_SIZE
#if defined(_MSC_VER)
#pragma warning(disable:4510 4512 4610)
#endif
#ifndef _ASSERTE
#ifdef _DEBUG
#define _ASSERTE(expr) \
do { if (!(expr) ) { ExtErr("_ASSERTE fired:\n\t%s\n", #expr); if (IsDebuggerPresent()) DebugBreak(); } } while (0)
#else
#define _ASSERTE(x)
#endif
#endif // ASSERTE
#ifdef _DEBUG
#define ASSERT_CHECK(expr, msg, reason) \
do { if (!(expr) ) { ExtOut(reason); ExtOut(msg); ExtOut(#expr); DebugBreak(); } } while (0)
#endif
// The native symbol reader dll name
#if defined(_AMD64_)
#define NATIVE_SYMBOL_READER_DLL W("Microsoft.DiaSymReader.Native.amd64.dll")
#elif defined(_X86_)
#define NATIVE_SYMBOL_READER_DLL W("Microsoft.DiaSymReader.Native.x86.dll")
#elif defined(_ARM_)
#define NATIVE_SYMBOL_READER_DLL W("Microsoft.DiaSymReader.Native.arm.dll")
#elif defined(_ARM64_)
// Use diasymreader until the package has an arm64 version - issue #7360
//#define NATIVE_SYMBOL_READER_DLL W("Microsoft.DiaSymReader.Native.arm64.dll")
#define NATIVE_SYMBOL_READER_DLL W("diasymreader.dll")
#endif
// PREFIX macros - Begin
// SOS does not have support for Contracts. Therefore we needed to duplicate
// some of the PREFIX infrastructure from inc\check.h in here.
// Issue - PREFast_:510 v4.51 does not support __assume(0)
#if (defined(_MSC_VER) && !defined(_PREFAST_)) || defined(_PREFIX_)
#if defined(_AMD64_)
// Empty methods that consist of UNREACHABLE() result in a zero-sized declspec(noreturn) method
// which causes the pdb file to make the next method declspec(noreturn) as well, thus breaking BBT
// Remove when we get a VC compiler that fixes VSW 449170
# define __UNREACHABLE() DebugBreak(); __assume(0);
#else
# define __UNREACHABLE() __assume(0)
#endif
#else
#define __UNREACHABLE() do { } while(true)
#endif
#if defined(_PREFAST_) || defined(_PREFIX_)
#define COMPILER_ASSUME_MSG(_condition, _message) if (!(_condition)) __UNREACHABLE();
#else
#if defined(DACCESS_COMPILE)
#define COMPILER_ASSUME_MSG(_condition, _message) do { } while (0)
#else
#if defined(_DEBUG)
#define COMPILER_ASSUME_MSG(_condition, _message) \
ASSERT_CHECK(_condition, _message, "Compiler optimization assumption invalid")
#else
#define COMPILER_ASSUME_MSG(_condition, _message) __assume(_condition)
#endif // _DEBUG
#endif // DACCESS_COMPILE
#endif // _PREFAST_ || _PREFIX_
#define PREFIX_ASSUME(_condition) \
COMPILER_ASSUME_MSG(_condition, "")
// PREFIX macros - End
class MethodTable;
#define MD_NOT_YET_LOADED ((DWORD_PTR)-1)
/*
* HANDLES
*
* The default type of handle is a strong handle.
*
*/
#define HNDTYPE_DEFAULT HNDTYPE_STRONG
#define HNDTYPE_WEAK_DEFAULT HNDTYPE_WEAK_LONG
#define HNDTYPE_WEAK_SHORT (0)
#define HNDTYPE_WEAK_LONG (1)
#define HNDTYPE_STRONG (2)
#define HNDTYPE_PINNED (3)
#define HNDTYPE_VARIABLE (4)
#define HNDTYPE_REFCOUNTED (5)
#define HNDTYPE_DEPENDENT (6)
#define HNDTYPE_ASYNCPINNED (7)
#define HNDTYPE_SIZEDREF (8)
#define HNDTYPE_WEAK_WINRT (9)
// Anything above this we consider abnormal and stop processing heap information
const int nMaxHeapSegmentCount = 1000;
class BaseObject
{
MethodTable *m_pMethTab;
};
const BYTE gElementTypeInfo[] = {
#define TYPEINFO(e,ns,c,s,g,ia,ip,if,im,gv) s,
#include "cortypeinfo.h"
#undef TYPEINFO
};
typedef struct tagLockEntry
{
tagLockEntry *pNext; // next entry
tagLockEntry *pPrev; // prev entry
DWORD dwULockID;
DWORD dwLLockID; // owning lock
WORD wReaderLevel; // reader nesting level
} LockEntry;
#define MAX_CLASSNAME_LENGTH 1024
enum EEFLAVOR {UNKNOWNEE, MSCOREE, MSCORWKS, MSCOREND};
#include "sospriv.h"
extern IXCLRDataProcess *g_clrData;
extern ISOSDacInterface *g_sos;
#include "dacprivate.h"
interface ICorDebugProcess;
extern ICorDebugProcess * g_pCorDebugProcess;
// This class is templated for easy modification. We may need to update the CachedString
// or related classes to use WCHAR instead of char in the future.
template <class T, int count, int size>
class StaticData
{
public:
StaticData()
{
for (int i = 0; i < count; ++i)
InUse[i] = false;
}
// Whether the individual data pointers in the cache are in use.
bool InUse[count];
// The actual data itself.
T Data[count][size];
// The number of arrays in the cache.
static const int Count;
// The size of each individual array.
static const int Size;
};
class CachedString
{
public:
CachedString();
CachedString(const CachedString &str);
~CachedString();
const CachedString &operator=(const CachedString &str);
// Returns the capacity of this string.
size_t GetStrLen() const
{
return mSize;
}
// Returns a mutable character pointer. Be sure not to write past the
// length of this string.
inline operator char *()
{
return mPtr;
}
// Returns a const char representation of this string.
inline operator const char *() const
{
return GetPtr();
}
// To ensure no AV's, any time a constant pointer is requested, we will
// return an empty string "" if we hit an OOM. This will only happen
// if we hit an OOM and do not check for it before using the string.
// If you request a non-const char pointer out of this class, it may be
// null (see operator char *).
inline const char *GetPtr() const
{
if (!mPtr || IsOOM())
return "";
return mPtr;
}
// Returns true if we ran out of memory trying to allocate the string
// or the refcount.
bool IsOOM() const
{
return mIndex == -2;
}
// allocate a string of the specified size. this will Clear() any
// previously allocated string. call IsOOM() to check for failure.
void Allocate(int size);
private:
// Copies rhs into this string.
void Copy(const CachedString &rhs);
// Clears this string, releasing any underlying memory.
void Clear();
// Creates a new string.
void Create();
// Sets an out of memory state.
void SetOOM();
private:
char *mPtr;
// The reference count. This may be null if there is only one copy
// of this string.
mutable unsigned int *mRefCount;
// mIndex contains the index of the cached pointer we are using, or:
// ~0 - poison value we initialize it to for debugging purposes
// -1 - mPtr points to a pointer we have new'ed
// -2 - We hit an oom trying to allocate either mCount or mPtr
int mIndex;
// contains the size of current string
int mSize;
private:
static StaticData<char, 4, 1024> cache;
};
// Things in this namespace should not be directly accessed/called outside of
// the output-related functions.
namespace Output
{
extern unsigned int g_bSuppressOutput;
extern unsigned int g_Indent;
extern unsigned int g_DMLEnable;
extern bool g_bDbgOutput;
extern bool g_bDMLExposed;
inline bool IsOutputSuppressed()
{ return g_bSuppressOutput > 0; }
inline void ResetIndent()
{ g_Indent = 0; }
inline void SetDebugOutputEnabled(bool enabled)
{ g_bDbgOutput = enabled; }
inline bool IsDebugOutputEnabled()
{ return g_bDbgOutput; }
inline void SetDMLExposed(bool exposed)
{ g_bDMLExposed = exposed; }
inline bool IsDMLExposed()
{ return g_bDMLExposed; }
enum FormatType
{
DML_None,
DML_MethodTable,
DML_MethodDesc,
DML_EEClass,
DML_Module,
DML_IP,
DML_Object,
DML_Domain,
DML_Assembly,
DML_ThreadID,
DML_ValueClass,
DML_DumpHeapMT,
DML_ListNearObj,
DML_ThreadState,
DML_PrintException,
DML_RCWrapper,
DML_CCWrapper,
DML_ManagedVar,
};
/**********************************************************************\
* This function builds a DML string for a ValueClass. If DML is *
* enabled, this function returns a DML string based on the format *
* type. Otherwise this returns a string containing only the hex value *
* of addr. *
* *
* Params: *
* mt - the method table of the ValueClass *
* addr - the address of the ValueClass *
* type - the format type to use to output this object *
* fill - whether or not to pad the hex value with zeros *
* *
\**********************************************************************/
CachedString BuildVCValue(CLRDATA_ADDRESS mt, CLRDATA_ADDRESS addr, FormatType type, bool fill = true);
/**********************************************************************\
* This function builds a DML string for an object. If DML is enabled, *
* this function returns a DML string based on the format type. *
* Otherwise this returns a string containing only the hex value of *
* addr. *
* *
* Params: *
* addr - the address of the object *
* type - the format type to use to output this object *
* fill - whether or not to pad the hex value with zeros *
* *
\**********************************************************************/
CachedString BuildHexValue(CLRDATA_ADDRESS addr, FormatType type, bool fill = true);
/**********************************************************************\
* This function builds a DML string for an managed variable name. *
* If DML is enabled, this function returns a DML string that will *
* enable the expansion of that managed variable using the !ClrStack *
* command to display the variable's fields, otherwise it will just *
* return the variable's name as a string.
* *
* Params: *
* expansionName - the current variable expansion string *
* frame - the frame that contains the variable of interest *
* simpleName - simple name of the managed variable *
* *
\**********************************************************************/
CachedString BuildManagedVarValue(__in_z LPCWSTR expansionName, ULONG frame, __in_z LPCWSTR simpleName, FormatType type);
CachedString BuildManagedVarValue(__in_z LPCWSTR expansionName, ULONG frame, int indexInArray, FormatType type); //used for array indices (simpleName = "[<indexInArray>]")
}
class NoOutputHolder
{
public:
NoOutputHolder(BOOL bSuppress = TRUE);
~NoOutputHolder();
private:
BOOL mSuppress;
};
class EnableDMLHolder
{
public:
EnableDMLHolder(BOOL enable);
~EnableDMLHolder();
private:
BOOL mEnable;
};
size_t CountHexCharacters(CLRDATA_ADDRESS val);
// Normal output.
void DMLOut(PCSTR format, ...); /* Prints out DML strings. */
void IfDMLOut(PCSTR format, ...); /* Prints given DML string ONLY if DML is enabled; prints nothing otherwise. */
void ExtOut(PCSTR Format, ...); /* Prints out to ExtOut (no DML). */
void ExtWarn(PCSTR Format, ...); /* Prints out to ExtWarn (no DML). */
void ExtErr(PCSTR Format, ...); /* Prints out to ExtErr (no DML). */
void ExtDbgOut(PCSTR Format, ...); /* Prints out to ExtOut in a checked build (no DML). */
void WhitespaceOut(int count); /* Prints out "count" number of spaces in the output. */
// Change indent for ExtOut
inline void IncrementIndent() { Output::g_Indent++; }
inline void DecrementIndent() { if (Output::g_Indent > 0) Output::g_Indent--; }
inline void ExtOutIndent() { WhitespaceOut(Output::g_Indent << 2); }
// DML Generation Methods
#define DMLListNearObj(addr) Output::BuildHexValue(addr, Output::DML_ListNearObj).GetPtr()
#define DMLDumpHeapMT(addr) Output::BuildHexValue(addr, Output::DML_DumpHeapMT).GetPtr()
#define DMLMethodTable(addr) Output::BuildHexValue(addr, Output::DML_MethodTable).GetPtr()
#define DMLMethodDesc(addr) Output::BuildHexValue(addr, Output::DML_MethodDesc).GetPtr()
#define DMLClass(addr) Output::BuildHexValue(addr, Output::DML_EEClass).GetPtr()
#define DMLModule(addr) Output::BuildHexValue(addr, Output::DML_Module).GetPtr()
#define DMLIP(ip) Output::BuildHexValue(ip, Output::DML_IP).GetPtr()
#define DMLObject(addr) Output::BuildHexValue(addr, Output::DML_Object).GetPtr()
#define DMLDomain(addr) Output::BuildHexValue(addr, Output::DML_Domain).GetPtr()
#define DMLAssembly(addr) Output::BuildHexValue(addr, Output::DML_Assembly).GetPtr()
#define DMLThreadID(id) Output::BuildHexValue(id, Output::DML_ThreadID, false).GetPtr()
#define DMLValueClass(mt, addr) Output::BuildVCValue(mt, addr, Output::DML_ValueClass).GetPtr()
#define DMLRCWrapper(addr) Output::BuildHexValue(addr, Output::DML_RCWrapper).GetPtr()
#define DMLCCWrapper(addr) Output::BuildHexValue(addr, Output::DML_CCWrapper).GetPtr()
#define DMLManagedVar(expansionName,frame,simpleName) Output::BuildManagedVarValue(expansionName, frame, simpleName, Output::DML_ManagedVar).GetPtr()
bool IsDMLEnabled();
#ifndef SOS_Assert
#define SOS_Assert(x)
#endif
void ConvertToLower(__out_ecount(len) char *buffer, size_t len);
extern const char * const DMLFormats[];
int GetHex(CLRDATA_ADDRESS addr, __out_ecount(len) char *out, size_t len, bool fill);
// A simple string class for mutable strings. We cannot use STL, so this is a stand in replacement
// for std::string (though it doesn't use the same interface).
template <class T, size_t (__cdecl *LEN)(const T *), errno_t (__cdecl *COPY)(T *, size_t, const T * _Src)>
class BaseString
{
public:
BaseString()
: mStr(0), mSize(0), mLength(0)
{
const size_t size = 64;
mStr = new T[size];
mSize = size;
mStr[0] = 0;
}
BaseString(const T *str)
: mStr(0), mSize(0), mLength(0)
{
CopyFrom(str, LEN(str));
}
BaseString(const BaseString<T, LEN, COPY> &rhs)
: mStr(0), mSize(0), mLength(0)
{
*this = rhs;
}
~BaseString()
{
Clear();
}
const BaseString<T, LEN, COPY> &operator=(const BaseString<T, LEN, COPY> &rhs)
{
Clear();
CopyFrom(rhs.mStr, rhs.mLength);
return *this;
}
const BaseString<T, LEN, COPY> &operator=(const T *str)
{
Clear();
CopyFrom(str, LEN(str));
return *this;
}
const BaseString<T, LEN, COPY> &operator +=(const T *str)
{
size_t len = LEN(str);
CopyFrom(str, len);
return *this;
}
const BaseString<T, LEN, COPY> &operator +=(const BaseString<T, LEN, COPY> &str)
{
CopyFrom(str.mStr, str.mLength);
return *this;
}
BaseString<T, LEN, COPY> operator+(const T *str) const
{
return BaseString<T, LEN, COPY>(mStr, mLength, str, LEN(str));
}
BaseString<T, LEN, COPY> operator+(const BaseString<T, LEN, COPY> &str) const
{
return BaseString<T, LEN, COPY>(mStr, mLength, str.mStr, str.mLength);
}
operator const T *() const
{
return mStr;
}
const T *c_str() const
{
return mStr;
}
size_t GetLength() const
{
return mLength;
}
private:
BaseString(const T * str1, size_t len1, const T * str2, size_t len2)
: mStr(0), mSize(0), mLength(0)
{
const size_t size = len1 + len2 + 1 + ((len1 + len2) >> 1);
mStr = new T[size];
mSize = size;
CopyFrom(str1, len1);
CopyFrom(str2, len2);
}
void Clear()
{
mLength = 0;
mSize = 0;
if (mStr)
{
delete [] mStr;
mStr = 0;
}
}
void CopyFrom(const T *str, size_t len)
{
if (mLength + len + 1 >= mSize)
Resize(mLength + len + 1);
COPY(mStr+mLength, mSize-mLength, str);
mLength += len;
}
void Resize(size_t size)
{
/* We always resize at least one half bigger than we need. When CopyFrom requests a resize
* it asks for the exact size that's needed to concatenate strings. However in practice
* it's common to add multiple strings together in a row, e.g.:
* String foo = "One " + "Two " + "Three " + "Four " + "\n";
* Ensuring the size of the string is bigger than we need, and that the minimum size is 64,
* we will cut down on a lot of needless resizes at the cost of a few bytes wasted in some
* cases.
*/
size += size >> 1;
if (size < 64)
size = 64;
T *newStr = new T[size];
if (mStr)
{
COPY(newStr, size, mStr);
delete [] mStr;
}
else
{
newStr[0] = 0;
}
mStr = newStr;
mSize = size;
}
private:
T *mStr;
size_t mSize, mLength;
};
typedef BaseString<char, strlen, strcpy_s> String;
typedef BaseString<WCHAR, _wcslen, wcscpy_s> WString;
template<class T>
void Flatten(__out_ecount(len) T *data, unsigned int len)
{
for (unsigned int i = 0; i < len; ++i)
if (data[i] < 32 || (data[i] > 126 && data[i] <= 255))
data[i] = '.';
data[len] = 0;
}
void Flatten(__out_ecount(len) char *data, unsigned int len);
/* Formats for the Format class. We support the following formats:
* Pointer - Same as %p.
* Hex - Same as %x (same as %p, but does not output preceding zeros.
* PrefixHex - Same as %x, but prepends 0x.
* Decimal - Same as %d.
* Strings and wide strings don't use this.
*/
class Formats
{
public:
enum Format
{
Default,
Pointer,
Hex,
PrefixHex,
Decimal,
};
};
enum Alignment
{
AlignLeft,
AlignRight
};
namespace Output
{
/* Defines how a value will be printed. This class understands how to format
* and print values according to the format and DML settings provided.
* The raw templated class handles the pointer/integer case. Support for
* character arrays and wide character arrays are handled by template
* specializations.
*
* Note that this class is not used directly. Instead use the typedefs and
* macros which define the type of data you are outputing (for example ObjectPtr,
* MethodTablePtr, etc).
*/
template <class T>
class Format
{
public:
Format(T value)
: mValue(value), mFormat(Formats::Default), mDml(Output::DML_None)
{
}
Format(T value, Formats::Format format, Output::FormatType dmlType)
: mValue(value), mFormat(format), mDml(dmlType)
{
}
Format(const Format<T> &rhs)
: mValue(rhs.mValue), mFormat(rhs.mFormat), mDml(rhs.mDml)
{
}
/* Prints out the value according to the Format and DML settings provided.
*/
void Output() const
{
if (IsDMLEnabled() && mDml != Output::DML_None)
{
const int len = GetDMLWidth(mDml);
char *buffer = (char*)alloca(len);
BuildDML(buffer, len, (CLRDATA_ADDRESS)mValue, mFormat, mDml);
DMLOut(buffer);
}
else
{
if (mFormat == Formats::Default || mFormat == Formats::Pointer)
{
ExtOut("%p", SOS_PTR(mValue));
}
else
{
const char *format = NULL;
if (mFormat == Formats::PrefixHex)
{
format = "0x%x";
}
else if (mFormat == Formats::Hex)
{
format = "%x";
}
else if (mFormat == Formats::Decimal)
{
format = "%d";
}
ExtOut(format, (__int32)mValue);
}
}
}
/* Prints out the value based on a specified width and alignment.
* Params:
* align - Whether the output should be left or right justified.
* width - The output width to fill.
* Note:
* This function guarantees that exactly width will be printed out (so if width is 24,
* exactly 24 characters will be printed), even if the output wouldn't normally fit
* in the space provided. This function makes no guarantees as to what part of the
* data will be printed in the case that width isn't wide enough.
*/
void OutputColumn(Alignment align, int width) const
{
bool leftAlign = align == AlignLeft;
if (IsDMLEnabled() && mDml != Output::DML_None)
{
const int len = GetDMLColWidth(mDml, width);
char *buffer = (char*)alloca(len);
BuildDMLCol(buffer, len, (CLRDATA_ADDRESS)mValue, mFormat, mDml, leftAlign, width);
DMLOut(buffer);
}
else
{
int precision = GetPrecision();
if (mFormat == Formats::Default || mFormat == Formats::Pointer)
{
if (precision > width)
precision = width;
ExtOut(leftAlign ? "%-*.*p" : "%*.*p", width, precision, SOS_PTR(mValue));
}
else
{
const char *format = NULL;
if (mFormat == Formats::PrefixHex)
{
format = leftAlign ? "0x%-*.*x" : "0x%*.*x";
width -= 2;
}
else if (mFormat == Formats::Hex)
{
format = leftAlign ? "%-*.*x" : "%*.*x";
}
else if (mFormat == Formats::Decimal)
{
format = leftAlign ? "%-*.*d" : "%*.*d";
}
if (precision > width)
precision = width;
ExtOut(format, width, precision, (__int32)mValue);
}
}
}
/* Converts this object into a Wide char string. This allows you to write the following code:
* WString foo = L"bar " + ObjectPtr(obj);
* Where ObjectPtr is a subclass/typedef of this Format class.
*/
operator WString() const
{
String str = *this;
const char *cstr = (const char *)str;
int len = MultiByteToWideChar(CP_ACP, 0, cstr, -1, NULL, 0);
WCHAR *buffer = (WCHAR *)alloca(len*sizeof(WCHAR));
MultiByteToWideChar(CP_ACP, 0, cstr, -1, buffer, len);
return WString(buffer);
}
/* Converts this object into a String object. This allows you to write the following code:
* String foo = "bar " + ObjectPtr(obj);
* Where ObjectPtr is a subclass/typedef of this Format class.
*/
operator String() const
{
if (IsDMLEnabled() && mDml != Output::DML_None)
{
const int len = GetDMLColWidth(mDml, 0);
char *buffer = (char*)alloca(len);
BuildDMLCol(buffer, len, (CLRDATA_ADDRESS)mValue, mFormat, mDml, false, 0);
return buffer;
}
else
{
char buffer[64];
if (mFormat == Formats::Default || mFormat == Formats::Pointer)
{
sprintf_s(buffer, _countof(buffer), "%p", (int *)(SIZE_T)mValue);
ConvertToLower(buffer, _countof(buffer));
}
else
{
const char *format = NULL;
if (mFormat == Formats::PrefixHex)
format = "0x%x";
else if (mFormat == Formats::Hex)
format = "%x";
else if (mFormat == Formats::Decimal)
format = "%d";
sprintf_s(buffer, _countof(buffer), format, (__int32)mValue);
ConvertToLower(buffer, _countof(buffer));
}
return buffer;
}
}
private:
int GetPrecision() const
{
if (mFormat == Formats::Hex || mFormat == Formats::PrefixHex)
{
ULONGLONG val = mValue;
int count = 0;
while (val)
{
val >>= 4;
count++;
}
if (count == 0)
count = 1;
return count;
}
else if (mFormat == Formats::Decimal)
{
T val = mValue;
int count = (val > 0) ? 0 : 1;
while (val)
{
val /= 10;
count++;
}
return count;
}
// mFormat == Formats::Pointer
return sizeof(int*)*2;
}
static inline void BuildDML(__out_ecount(len) char *result, int len, CLRDATA_ADDRESS value, Formats::Format format, Output::FormatType dmlType)
{
BuildDMLCol(result, len, value, format, dmlType, true, 0);
}
static int GetDMLWidth(Output::FormatType dmlType)
{
return GetDMLColWidth(dmlType, 0);
}
static void BuildDMLCol(__out_ecount(len) char *result, int len, CLRDATA_ADDRESS value, Formats::Format format, Output::FormatType dmlType, bool leftAlign, int width)
{
char hex[64];
int count = GetHex(value, hex, _countof(hex), format != Formats::Hex);
int i = 0;
if (!leftAlign)
{
for (; i < width - count; ++i)
result[i] = ' ';
result[i] = 0;
}
int written = sprintf_s(result+i, len - i, DMLFormats[dmlType], hex, hex);
SOS_Assert(written != -1);
if (written != -1)
{
for (i = i + written; i < width; ++i)
result[i] = ' ';
result[i] = 0;
}
}
static int GetDMLColWidth(Output::FormatType dmlType, int width)
{
return 1 + 4*sizeof(int*) + (int)strlen(DMLFormats[dmlType]) + width;
}
private:
T mValue;
Formats::Format mFormat;
Output::FormatType mDml;
};
/* Format class used for strings.
*/
template <>
class Format<const char *>
{
public:
Format(const char *value)
: mValue(value)
{
}
Format(const Format<const char *> &rhs)
: mValue(rhs.mValue)
{
}
void Output() const
{
if (IsDMLEnabled())
DMLOut("%s", mValue);
else
ExtOut("%s", mValue);
}
void OutputColumn(Alignment align, int width) const
{
int precision = (int)strlen(mValue);
if (precision > width)
precision = width;
const char *format = align == AlignLeft ? "%-*.*s" : "%*.*s";
if (IsDMLEnabled())
DMLOut(format, width, precision, mValue);
else
ExtOut(format, width, precision, mValue);
}
private:
const char *mValue;
};
/* Format class for wide char strings.
*/
template <>
class Format<const WCHAR *>
{
public:
Format(const WCHAR *value)
: mValue(value)
{
}
Format(const Format<const WCHAR *> &rhs)
: mValue(rhs.mValue)
{
}
void Output() const
{
if (IsDMLEnabled())
DMLOut("%S", mValue);
else
ExtOut("%S", mValue);
}
void OutputColumn(Alignment align, int width) const
{