File: Debug.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (1097 lines) | stat: -rw-r--r-- 40,357 bytes parent folder | download | duplicates (7)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
//------------------------------------------------------------------------------
// <copyright file="Debug.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>                                                                
//------------------------------------------------------------------------------

namespace System.Web.Util {
    using Microsoft.Win32;
    using Microsoft.Win32.SafeHandles;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Globalization;
    using System.Reflection;
    using System.Runtime.ConstrainedExecution;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Security.Permissions;
    using System.Threading;
    using System.Runtime.Versioning;

    internal static class Debug {

        internal const string   TAG_INTERNAL = "Internal";
        internal const string   TAG_EXTERNAL = "External";
        internal const string   TAG_ALL      = "*";

        internal const string   DATE_FORMAT = @"yyyy/MM/dd HH:mm:ss.ffff";
        internal const string   TIME_FORMAT = @"HH:mm:ss:ffff";

        // Some of these APIs must be always available, not #ifdefed away.
        [SuppressUnmanagedCodeSecurity]
        private static partial class NativeMethods {
            [DllImport("kernel32.dll")]
            internal extern static bool IsDebuggerPresent();
        }

#if DBG
        private static partial class NativeMethods {
            [DllImport("kernel32.dll")]
            internal extern static void DebugBreak();

            [DllImport("kernel32.dll")]
            internal extern static int GetCurrentProcessId();

            [DllImport("kernel32.dll")]
            internal extern static int GetCurrentThreadId();

            [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            internal extern static IntPtr GetCurrentProcess();

            [DllImport("kernel32.dll", SetLastError=true)]
            internal extern static bool TerminateProcess(HandleRef processHandle, int exitCode);

            [DllImport("kernel32.dll", CharSet=CharSet.Auto, BestFitMapping=false)]
            internal extern static void OutputDebugString(string message);

            internal const int PM_NOREMOVE = 0x0000;
            internal const int PM_REMOVE = 0x0001;

            [StructLayout(LayoutKind.Sequential)]
            internal struct MSG {
                internal IntPtr   hwnd;
                internal int      message;
                internal IntPtr   wParam;
                internal IntPtr   lParam;
                internal int      time;
                internal int      pt_x;
                internal int      pt_y;
            }

            [DllImport("user32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
            internal extern static bool PeekMessage([In, Out] ref MSG msg, HandleRef hwnd, int msgMin, int msgMax, int remove);

            internal const int 
                MB_OK = 0x00000000,
                MB_OKCANCEL = 0x00000001,
                MB_ABORTRETRYIGNORE = 0x00000002,
                MB_YESNOCANCEL = 0x00000003,
                MB_YESNO = 0x00000004,
                MB_RETRYCANCEL = 0x00000005,
                MB_ICONHAND = 0x00000010,
                MB_ICONQUESTION = 0x00000020,
                MB_ICONEXCLAMATION = 0x00000030,
                MB_ICONASTERISK = 0x00000040,
                MB_USERICON = 0x00000080,
                MB_ICONWARNING = 0x00000030,
                MB_ICONERROR = 0x00000010,
                MB_ICONINFORMATION = 0x00000040,
                MB_DEFBUTTON1 = 0x00000000,
                MB_DEFBUTTON2 = 0x00000100,
                MB_DEFBUTTON3 = 0x00000200,
                MB_DEFBUTTON4 = 0x00000300,
                MB_APPLMODAL = 0x00000000,
                MB_SYSTEMMODAL = 0x00001000,
                MB_TASKMODAL = 0x00002000,
                MB_HELP = 0x00004000,
                MB_NOFOCUS = 0x00008000,
                MB_SETFOREGROUND = 0x00010000,
                MB_DEFAULT_DESKTOP_ONLY = 0x00020000,
                MB_TOPMOST = 0x00040000,
                MB_RIGHT = 0x00080000,
                MB_RTLREADING = 0x00100000,
                MB_SERVICE_NOTIFICATION = 0x00200000,
                MB_SERVICE_NOTIFICATION_NT3X = 0x00040000,
                MB_TYPEMASK = 0x0000000F,
                MB_ICONMASK = 0x000000F0,
                MB_DEFMASK = 0x00000F00,
                MB_MODEMASK = 0x00003000,
                MB_MISCMASK = 0x0000C000;

            internal const int
                IDOK = 1,
                IDCANCEL = 2,
                IDABORT = 3,
                IDRETRY = 4,
                IDIGNORE = 5,
                IDYES = 6,
                IDNO = 7,
                IDCLOSE = 8,
                IDHELP = 9;


            [DllImport("user32.dll", CharSet=CharSet.Auto, BestFitMapping=false)]
            internal extern static int MessageBox(HandleRef hWnd, string text, string caption, int type);

            internal static readonly IntPtr HKEY_LOCAL_MACHINE = unchecked((IntPtr)(int)0x80000002);

            internal const int READ_CONTROL           = 0x00020000;
            internal const int STANDARD_RIGHTS_READ   = READ_CONTROL;

            internal const int SYNCHRONIZE            = 0x00100000;

            internal const int KEY_QUERY_VALUE        = 0x0001;
            internal const int KEY_ENUMERATE_SUB_KEYS = 0x0008;
            internal const int KEY_NOTIFY             = 0x0010;


            internal const int KEY_READ               = ((STANDARD_RIGHTS_READ |
                                                               KEY_QUERY_VALUE |
                                                               KEY_ENUMERATE_SUB_KEYS |
                                                               KEY_NOTIFY)
                                                              &
                                                              (~SYNCHRONIZE));

            internal const int REG_NOTIFY_CHANGE_NAME       = 1;
            internal const int REG_NOTIFY_CHANGE_LAST_SET   = 4;


            [DllImport("advapi32.dll", CharSet=CharSet.Auto, BestFitMapping=false, SetLastError=true)]
            internal extern static int RegOpenKeyEx(IntPtr hKey, string lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult);

            [DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true)]
            internal extern static int RegNotifyChangeKeyValue(SafeRegistryHandle hKey, bool watchSubTree, uint notifyFilter, SafeWaitHandle regEvent, bool async);
        }

        private class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid {

            // Note: Officially -1 is the recommended invalid handle value for
            // registry keys, but we'll also get back 0 as an invalid handle from
            // RegOpenKeyEx.

            [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode=true)]
            [ResourceExposure(ResourceScope.Machine)]
            internal SafeRegistryHandle() : base(true) {}

            [DllImport("advapi32.dll"),
             SuppressUnmanagedCodeSecurity,
             ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
            private static extern int RegCloseKey(IntPtr hKey);

            override protected bool ReleaseHandle()
            {
                // Returns a Win32 error code, 0 for success
                int r = RegCloseKey(handle);
                return r == 0;
            }
        }

        private enum TagValue {
            Disabled = 0,
            Enabled = 1,
            Break = 2,

            Min = Disabled,
            Max = Break,
        }

        private const string            TAG_ASSERT = "Assert";
        private const string            TAG_ASSERT_BREAK = "AssertBreak";

        private const string            TAG_DEBUG_VERBOSE = "DebugVerbose";
        private const string            TAG_DEBUG_MONITOR = "DebugMonitor";
        private const string            TAG_DEBUG_PREFIX = "DebugPrefix";
        private const string            TAG_DEBUG_THREAD_PREFIX = "DebugThreadPrefix";

        private const string            PRODUCT = "Microsoft .NET Framework";
        private const string            COMPONENT = "System.Web";

        private static string           s_regKeyName = @"Software\Microsoft\ASP.NET\Debug";
        private static string           s_listenKeyName = @"Software\Microsoft";

        private static bool             s_assert;
        private static bool             s_assertBreak;

        private static bool             s_includePrefix;
        private static bool             s_includeThreadPrefix;
        private static bool             s_monitor;

        private static object           s_lock;
        private static volatile bool    s_inited;
        private static ReadOnlyCollection<Tag>  s_tagDefaults;
        private static List<Tag>        s_tags;

        private static AutoResetEvent       s_notifyEvent;
        private static RegisteredWaitHandle s_waitHandle;
        private static SafeRegistryHandle   s_regHandle;
        private static bool                 s_stopMonitoring;

        private static Hashtable        s_tableAlwaysValidate;
        private static Type[]           s_DumpArgs;
        private static Type[]           s_ValidateArgs;

        private class Tag {
            string      _name;
            TagValue    _value;
            int         _prefixLength;

            internal Tag(string name, TagValue value) {
                _name = name;
                _value = value;

                if (_name[_name.Length - 1] == '*') {
                    _prefixLength = _name.Length - 1;
                }
                else {
                    _prefixLength = -1;
                }
            }

            internal string Name {
                get {return _name;}
            }

            internal TagValue Value {
                get {return _value;}
            }

            internal int PrefixLength {
                get {return _prefixLength;}
            }
        }

        static Debug() {
            s_lock = new object();
        }

        private static void EnsureInit() {
            bool continueInit = false;

            if (!s_inited) {
                lock (s_lock) {
                    if (!s_inited) {
                        s_tableAlwaysValidate = new Hashtable();
                        s_DumpArgs = new Type[1] {typeof(string)}; 
                        s_ValidateArgs = new Type[0];              

                        List<Tag> tagDefaults = new List<Tag>();
                        tagDefaults.Add(new Tag(TAG_ALL, TagValue.Disabled));
                        tagDefaults.Add(new Tag(TAG_INTERNAL, TagValue.Enabled));
                        tagDefaults.Add(new Tag(TAG_EXTERNAL, TagValue.Enabled));
                        tagDefaults.Add(new Tag(TAG_ASSERT, TagValue.Break));
                        tagDefaults.Add(new Tag(TAG_ASSERT_BREAK, TagValue.Disabled));
                        tagDefaults.Add(new Tag(TAG_DEBUG_VERBOSE, TagValue.Enabled));
                        tagDefaults.Add(new Tag(TAG_DEBUG_MONITOR, TagValue.Enabled));
                        tagDefaults.Add(new Tag(TAG_DEBUG_PREFIX, TagValue.Enabled));
                        tagDefaults.Add(new Tag(TAG_DEBUG_THREAD_PREFIX, TagValue.Enabled));

                        s_tagDefaults = tagDefaults.AsReadOnly();
                        s_tags = new List<Tag>(s_tagDefaults);
                        GetBuiltinTagValues();

                        continueInit = true;
                        s_inited = true;
                    }
                }
            }

            // Work to do outside the init lock.
            if (continueInit) {
                ReadTagsFromRegistry();
                Trace(TAG_DEBUG_VERBOSE, "Debugging package initialized");

                // Need to read tags before starting to monitor in order to get TAG_DEBUG_MONITOR
                StartRegistryMonitor();
            }
        }

        private static bool StringEqualsIgnoreCase(string s1, string s2) {
            return StringComparer.OrdinalIgnoreCase.Equals(s1, s2);
        }

        [RegistryPermission(SecurityAction.Assert, Unrestricted=true)]
        private static void WriteTagsToRegistry() {
            try {
                using (RegistryKey key = Registry.LocalMachine.CreateSubKey(s_regKeyName)) {
                    List<Tag> tags = s_tags;
                    foreach (Tag tag in tags) {
                        key.SetValue(tag.Name, tag.Value, RegistryValueKind.DWord);
                    }
                }
            }
            catch {
            }
        }

        private static void GetBuiltinTagValues() {
            // Use GetTagValue instead of IsTagEnabled because it does not call EnsureInit
            // and potentially recurse.
            s_assert              = (GetTagValue(TAG_ASSERT) != TagValue.Disabled);
            s_assertBreak         = (GetTagValue(TAG_ASSERT_BREAK) != TagValue.Disabled);
            s_includePrefix       = (GetTagValue(TAG_DEBUG_PREFIX) != TagValue.Disabled);
            s_includeThreadPrefix = (GetTagValue(TAG_DEBUG_THREAD_PREFIX) != TagValue.Disabled);
            s_monitor             = (GetTagValue(TAG_DEBUG_MONITOR) != TagValue.Disabled);
        }

        [RegistryPermission(SecurityAction.Assert, Unrestricted=true)]
        private static void ReadTagsFromRegistry() {
            lock (s_lock) {
                try {
                    List<Tag> tags = new List<Tag>(s_tagDefaults);
                    string[] names = null;

                    bool writeTags = false;
                    using (RegistryKey key = Registry.LocalMachine.OpenSubKey(s_regKeyName, false)) {
                        if (key != null) {
                            names = key.GetValueNames();
                            foreach (string name in names) {
                                TagValue value = TagValue.Disabled;
                                try {
                                    TagValue keyvalue = (TagValue) key.GetValue(name);
                                    if (TagValue.Min <= keyvalue && keyvalue <= TagValue.Max) {
                                        value = keyvalue;
                                    }
                                    else {
                                        writeTags = true;
                                    }
                                }
                                catch {
                                    writeTags = true;
                                }

                                // Add tag to list, making sure it is unique.
                                Tag tag = new Tag(name, (TagValue) value);
                                bool found = false;
                                for (int i = 0; i < s_tagDefaults.Count; i++) {
                                    if (StringEqualsIgnoreCase(name, tags[i].Name)) {
                                        found = true;
                                        tags[i] = tag;
                                        break;
                                    }
                                }

                                if (!found) {
                                    tags.Add(tag);
                                }
                            }
                        }
                    }

                    s_tags = tags;
                    GetBuiltinTagValues();

                    // Write tags out if there was an invalid value or 
                    // not all default tags are present.
                    if (writeTags || (names != null && names.Length < tags.Count)) {
                        WriteTagsToRegistry();
                    }
                }
                catch {
                    s_tags = new List<Tag>(s_tagDefaults);
                }
            }
        }

        private static void StartRegistryMonitor() {
            if (!s_monitor) {
                Trace(TAG_DEBUG_VERBOSE, "WARNING: Registry monitoring disabled, changes during process execution will not be recognized."); 
                return;
            }

            Trace(TAG_DEBUG_VERBOSE, "Monitoring registry key " + s_listenKeyName + " for changes.");

            // Event used to notify of changes.
            s_notifyEvent = new AutoResetEvent(false);

            // Register a wait on the event.
            s_waitHandle = ThreadPool.RegisterWaitForSingleObject(s_notifyEvent, OnRegChangeKeyValue, null, -1, false);

            // Monitor the registry.
            MonitorRegistryForOneChange();
        }

        private static void StopRegistryMonitor() {
            // Cleanup allocated handles
            s_stopMonitoring = true;

            if (s_regHandle != null) {
                s_regHandle.Close();
                s_regHandle = null;
            }

            if (s_waitHandle != null) {
                s_waitHandle.Unregister(s_notifyEvent);
                s_waitHandle = null;
            }

            if (s_notifyEvent != null) {
                s_notifyEvent.Close();
                s_notifyEvent = null;
            }

            Trace(TAG_DEBUG_VERBOSE, "Registry monitoring stopped."); 
        }

        public static void OnRegChangeKeyValue(object state, bool timedOut) {
            if (!s_stopMonitoring) {
                if (timedOut) {
                    StopRegistryMonitor();
                }
                else {
                    // Monitor again
                    MonitorRegistryForOneChange();

                    // Once we're monitoring, read the changes to the registry.
                    // We have to do this after we start monitoring in order
                    // to catch all changes to the registry.
                    ReadTagsFromRegistry();
                }
            }
        }

        private static void MonitorRegistryForOneChange() {
            // Close the open reg handle
            if (s_regHandle != null) {
                s_regHandle.Close();
                s_regHandle = null;
            }

            // Open the reg key
            int result = NativeMethods.RegOpenKeyEx(NativeMethods.HKEY_LOCAL_MACHINE, s_listenKeyName, 0, NativeMethods.KEY_READ, out s_regHandle);
            if (result != 0) {
                StopRegistryMonitor();
                return;
            }

            // Listen for changes.
            result = NativeMethods.RegNotifyChangeKeyValue(
                    s_regHandle, 
                    true, 
                    NativeMethods.REG_NOTIFY_CHANGE_NAME | NativeMethods.REG_NOTIFY_CHANGE_LAST_SET,
                    s_notifyEvent.SafeWaitHandle,
                    true);

            if (result != 0) {
                StopRegistryMonitor();
            }
        }

        private static Tag FindMatchingTag(string name, bool exact) {
            List<Tag> tags = s_tags;

            // Look for exact match first
            foreach (Tag tag in tags) {
                if (StringEqualsIgnoreCase(name, tag.Name)) {
                    return tag;
                }
            }

            if (exact) {
                return null;
            }

            Tag longestTag = null;
            int longestPrefix = -1;
            foreach (Tag tag in tags) {
                if (    tag.PrefixLength > longestPrefix && 
                        0 == string.Compare(name, 0, tag.Name, 0, tag.PrefixLength, StringComparison.OrdinalIgnoreCase)) {

                    longestTag = tag;
                    longestPrefix = tag.PrefixLength;
                }
            }

            return longestTag;
        }

        private static TagValue GetTagValue(string name) {
            Tag tag = FindMatchingTag(name, false);
            if (tag != null) {
                return tag.Value;
            }
            else {
                return TagValue.Disabled;
            }
        }

        [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
        private static bool TraceBreak(string tagName, string message, Exception e, bool includePrefix) {
            EnsureInit();

            TagValue tagValue = GetTagValue(tagName);
            if (tagValue == TagValue.Disabled) {
                return false;
            }

            bool isAssert = object.ReferenceEquals(tagName, TAG_ASSERT);
            if (isAssert) {
                tagName = "";
            }

            string exceptionMessage = null;
            if (e != null) {
                string httpCode = null;
                string errorCode = null;

                if (e is HttpException) {
                    httpCode = " _httpCode=" + ((HttpException)e).GetHttpCode().ToString(CultureInfo.InvariantCulture) + " ";
                }

                if (e is ExternalException) {
                    // note that HttpExceptions are ExternalExceptions
                    errorCode = "_hr=0x" + ((ExternalException)e).ErrorCode.ToString("x", CultureInfo.InvariantCulture);
                }

                // Use e.ToString() in order to get inner exception
                if (errorCode != null) {
                    exceptionMessage = "Exception " + e.ToString() + "\n" + httpCode + errorCode;
                }
                else {
                    exceptionMessage = "Exception " + e.ToString();
                }
            }

            if (string.IsNullOrEmpty(message) & exceptionMessage != null) {
                message = exceptionMessage;
                exceptionMessage = null;
            }

            string traceFormat;
            int idThread = 0;
            int idProcess = 0;

            if (!includePrefix || !s_includePrefix) {
                traceFormat = "{4}\n{5}";
            }
            else {
                if (s_includeThreadPrefix) {
                    idThread = NativeMethods.GetCurrentThreadId();
                    idProcess = NativeMethods.GetCurrentProcessId();
                    traceFormat = "[0x{0:x}.{1:x} {2} {3}] {4}\n{5}";
                }
                else {
                    traceFormat = "[{2} {3}] {4}\n{5}";
                }
            }

            string suffix = "";
            if (exceptionMessage != null) {
                suffix += exceptionMessage + "\n";
            }

            bool doBreak = (tagValue == TagValue.Break);
            if (doBreak && !isAssert) {
                suffix += "Breaking into debugger...\n";
            }

            string traceMessage = string.Format(CultureInfo.InvariantCulture, traceFormat, idProcess, idThread, COMPONENT, tagName, message, suffix);

            NativeMethods.OutputDebugString(traceMessage);

            return doBreak;
        }

        private class MBResult {
            internal int Result;
        }

        [ResourceExposure(ResourceScope.None)]
        static bool DoAssert(string message) {
            if (!s_assert) {
                return false;
            }

            // Skip 2 frames - one for this function, one for
            // the public Assert function that called this function.
            System.Diagnostics.StackFrame frame = new System.Diagnostics.StackFrame(2, true);
            System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(2, true);

            string fileName = frame.GetFileName();
            int lineNumber = frame.GetFileLineNumber();

            string traceFormat;
            if (!string.IsNullOrEmpty(fileName)) {
                traceFormat = "ASSERTION FAILED: {0}\nFile: {1}:{2}\nStack trace:\n{3}";
            }
            else {
                traceFormat = "ASSERTION FAILED: {0}\nStack trace:\n{3}";
            }

            string traceMessage = string.Format(CultureInfo.InvariantCulture, traceFormat, message, fileName, lineNumber, trace.ToString());

            if (!TraceBreak(TAG_ASSERT, traceMessage, null, true)) {
                // If the value of "Assert" is not TagValue.Break, then don't even ask user.
                return false;
            }

            if (s_assertBreak) {
                // If "AssertBreak" is enabled, then always break.
                return true;
            }

            string dialogFormat;
            if (!string.IsNullOrEmpty(fileName)) {
                dialogFormat = 
@"Failed expression: {0}
File: {1}:{2}
Component: {3}
PID={4} TID={5}
Stack trace:
{6}

A=Exit process R=Debug I=Continue";
            }
            else {
                dialogFormat = 
@"Failed expression: {0}
(no file information available)
Component: {3}
PID={4} TID={5}
Stack trace:
{6}

A=Exit process R=Debug I=Continue";
            }

            string dialogMessage = string.Format(
                CultureInfo.InvariantCulture,
                dialogFormat,
                message,
                fileName, lineNumber,
                COMPONENT,
                NativeMethods.GetCurrentProcessId(), NativeMethods.GetCurrentThreadId(),
                trace.ToString());

            MBResult mbResult = new MBResult();

            Thread thread = new Thread(
                delegate() {
                    for (int i = 0; i < 100; i++) {
                        NativeMethods.MSG msg = new NativeMethods.MSG();
                        NativeMethods.PeekMessage(ref msg, new HandleRef(mbResult, IntPtr.Zero), 0, 0, NativeMethods.PM_REMOVE);
                    }

                    mbResult.Result = NativeMethods.MessageBox(new HandleRef(mbResult, IntPtr.Zero), dialogMessage, PRODUCT + " Assertion",                
                        NativeMethods.MB_SERVICE_NOTIFICATION | 
                        NativeMethods.MB_TOPMOST |
                        NativeMethods.MB_ABORTRETRYIGNORE | 
                        NativeMethods.MB_ICONEXCLAMATION);
                }
            );

            thread.Start();
            thread.Join();

            if (mbResult.Result == NativeMethods.IDABORT) {
                IntPtr currentProcess = NativeMethods.GetCurrentProcess();
                NativeMethods.TerminateProcess(new HandleRef(mbResult, currentProcess), 1);
            }

            return mbResult.Result == NativeMethods.IDRETRY;
        }
#endif

        //
        // Sends the message to the debugger if the tag is enabled.
        // Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
        //
        [System.Diagnostics.Conditional("DBG")]
        internal static void Trace(string tagName, string message) {
#if DBG
            if (TraceBreak(tagName, message, null, true)) {
                Break();
            }
#endif
        }

        //
        // Sends the message to the debugger if the tag is enabled.
        // Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
        //
        [System.Diagnostics.Conditional("DBG")]
        internal static void Trace(string tagName, string message, bool includePrefix) {
#if DBG
            if (TraceBreak(tagName, message, null, includePrefix)) {
                Break();
            }
#endif
        }

        //
        // Sends the message to the debugger if the tag is enabled.
        // Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
        //
        [System.Diagnostics.Conditional("DBG")]
        internal static void Trace(string tagName, string message, Exception e) {
#if DBG
            if (TraceBreak(tagName, message, e, true)) {
                Break();
            }
#endif
        }

        //
        // Sends the message to the debugger if the tag is enabled.
        // Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
        //
        [System.Diagnostics.Conditional("DBG")]
        internal static void Trace(string tagName, Exception e) {
#if DBG
            if (TraceBreak(tagName, null, e, true)) {
                Break();
            }
#endif
        }

        //
        // Sends the message to the debugger if the tag is enabled.
        // Also breaks into the debugger the value of the tag is 2 (TagValue.Break).
        //
        [System.Diagnostics.Conditional("DBG")]
        internal static void Trace(string tagName, string message, Exception e, bool includePrefix) {
#if DBG
            if (TraceBreak(tagName, message, e, includePrefix)) {
                Break();
            }
#endif
        }

#if DBG
#endif

        [System.Diagnostics.Conditional("DBG")]
        public static void TraceException(String tagName, Exception e) {
#if DBG
            if (TraceBreak(tagName, null, e, true)) {
                Break();
            }
#endif
        }


        //
        // If the assertion is false and the 'Assert' tag is enabled:
        //      * Send a message to the debugger.
        //      * If the 'AssertBreak' tag is enabled, immediately break into the debugger
        //      * Else display a dialog box asking the user to Abort, Retry (break), or Ignore
        //
        [System.Diagnostics.Conditional("DBG")]
        internal static void Assert(bool assertion, string message) {
#if DBG
            EnsureInit();
            if (assertion == false) {
                if (DoAssert(message)) {
                    Break();
                }
            }
#endif
        }


        //
        // If the assertion is false and the 'Assert' tag is enabled:
        //      * Send a message to the debugger.
        //      * If the 'AssertBreak' tag is enabled, immediately break into the debugger
        //      * Else display a dialog box asking the user to Abort, Retry (break), or Ignore
        //
        [System.Diagnostics.Conditional("DBG")]
        [ResourceExposure(ResourceScope.None)]
        internal static void Assert(bool assertion) {
#if DBG
            EnsureInit();
            if (assertion == false) {
                if (DoAssert(null)) {
                    Break();
                }
            }
#endif
        }

        //
        // Like Assert, but the assertion is always considered to be false.
        //
        [System.Diagnostics.Conditional("DBG")]
        [ResourceExposure(ResourceScope.None)]
        internal static void Fail(string message) {
#if DBG
            Assert(false, message);
#endif
        }

        //
        // Returns true if the tag is enabled, false otherwise.
        // Note that the tag needn't be an exact match.
        //
        [ResourceExposure(ResourceScope.None)]
        internal static bool IsTagEnabled(string tagName) {
#if DBG
            EnsureInit();
            return GetTagValue(tagName) != TagValue.Disabled;
#else
            return false;
#endif
        }

        //
        // Returns true if the tag present. 
        // This function chekcs for an exact match.
        //
        [ResourceExposure(ResourceScope.None)]
        internal static bool IsTagPresent(string tagName) {
#if DBG
            EnsureInit();
            return FindMatchingTag(tagName, true) != null;
#else
            return false;
#endif
        }

        // Returns a value indicating whether a debugger is attached to the process.
        // We don't #ifdef this away since we might need to change behavior based
        // on whether one is attached.
        internal static bool IsDebuggerPresent() {
            return (NativeMethods.IsDebuggerPresent() || System.Diagnostics.Debugger.IsAttached);
        }

        //
        // Breaks into the debugger, or launches one if not yet attached.
        //
        [System.Diagnostics.Conditional("DBG")]
        [ResourceExposure(ResourceScope.None)]
        internal static void Break() {
#if DBG
            if (NativeMethods.IsDebuggerPresent()) {
                NativeMethods.DebugBreak();
            }
            else if (!System.Diagnostics.Debugger.IsAttached) {
                System.Diagnostics.Debugger.Launch();
            }
            else {
                System.Diagnostics.Debugger.Break();            
            }
#endif
        }


        //
        // Tells the debug system to always validate calls for a
        // particular tag. This is useful for temporarily enabling
        // validation in stress tests or other situations where you
        // may not have control over the debug tags that are enabled
        // on a particular machine.
        // 
        [System.Diagnostics.Conditional("DBG")]
        internal static void AlwaysValidate(string tagName) {
#if DBG
            EnsureInit();
            s_tableAlwaysValidate[tagName] = tagName;
#endif
        }


        //
        // Throws an exception if the assertion is not valid.
        // Use this function from a DebugValidate method where
        // you would otherwise use Assert.
        //
        [System.Diagnostics.Conditional("DBG")]
        internal static void CheckValid(bool assertion, string message) {
#if DBG
            if (!assertion) {
                throw new Exception(message);
            }
#endif
        }

        //
        // Calls DebugValidate on an object if such a method exists.
        //
        // This method should be used from implementations of DebugValidate
        // where it is unknown whether an object has a DebugValidate method.
        // For example, the DoubleLink class uses it to validate the
        // item of type Object which it points to.
        //
        // This method should NOT be used when code wants to conditionally
        // validate an object and have a failed validation caught in an assert.
        // Use Debug.Validate(tagName, obj) for that purpose.
        //
        [System.Diagnostics.Conditional("DBG")]
        [ResourceExposure(ResourceScope.None)]
        internal static void Validate(Object obj) {
#if DBG
            Type        type;
            MethodInfo  mi;

            if (obj != null) {
                type = obj.GetType();

                mi = type.GetMethod(
                        "DebugValidate", 
                        BindingFlags.NonPublic | BindingFlags.Instance,
                        null,
                        s_ValidateArgs,
                        null);

                if (mi != null) {
                    object[] tempIndex = null;
                    mi.Invoke(obj, tempIndex);
                }
            }
#endif
        }

        // Ensures that the bounds provided to an array-consuming method are correct.
        // Because this method is on the Debug type, it should only be used in debugging
        // code and should not be depended on for user input sanitization (since the
        // compiler won't emit calls to it.)
        [System.Diagnostics.Conditional("DBG")]
        internal static void ValidateArrayBounds<T>(T[] array, int offset, int count) {
#if DBG
            // these are the same checks as in the ArraySegment<T> ctor
            Assert(array != null, "Array cannot be null.");
            Assert(offset >= 0, "Offset must be non-negative.");
            Assert(count >= 0, "Count must be non-negative.");
            Assert(array.Length - offset >= count, "Invalid offset.");
#endif
        }

        //
        // Validates an object is the "Validate" tag is enabled, or when
        // the "Validate" tag is not disabled and the given 'tag' is enabled.
        // An Assertion is made if the validation fails.
        //
        [System.Diagnostics.Conditional("DBG")]
        [ResourceExposure(ResourceScope.None)]
        internal static void Validate(string tagName, Object obj) {
#if DBG
            EnsureInit();

            if (    obj != null 
                    && (    IsTagEnabled("Validate")
                            ||  (   !IsTagPresent("Validate") 
                                    && (   s_tableAlwaysValidate[tagName] != null 
                                           ||  IsTagEnabled(tagName))))) {
                try {
                    Debug.Validate(obj);
                }
                catch (Exception e) {
                    Debug.Assert(false, "Validate failed: " + e.InnerException.Message);
                }
#pragma warning disable 1058
                catch {
                    Debug.Assert(false, "Validate failed.  Non-CLS compliant exception caught.");
                }
#pragma warning restore 1058
            }
#endif
        }

#if DBG

        //
        // Calls DebugDescription on an object to get its description.
        //
        // This method should only be used in implementations of DebugDescription
        // where it is not known whether a nested objects has an implementation
        // of DebugDescription. For example, the double linked list class uses
        // GetDescription to get the description of the item it points to.
        //
        // This method should NOT be used when you want to conditionally
        // dump an object. Use Debug.Dump instead.
        //
        // @param obj      The object to call DebugDescription on. May be null.
        // @param indent   A prefix for each line in the description. This is used
        //                 to allow the nested display of objects within other objects.
        //                 The indent is usually a multiple of four spaces.
        //
        // @return         The description.
        //
        [ReflectionPermission(SecurityAction.Assert, Unrestricted=true)]
        internal static string GetDescription(Object obj, string indent) {
            string      description;
            Type        type;
            MethodInfo  mi;
            Object[]   parameters;

            if (obj == null) {
                description = "\n";
            }
            else {
                type = obj.GetType();
                mi = type.GetMethod(
                        "DebugDescription", 
                        BindingFlags.NonPublic | BindingFlags.Instance,
                        null,
                        s_DumpArgs,
                        null);
                        
                if (mi == null || mi.ReturnType != typeof(string)) {
                    description = indent + obj.ToString();
                }
                else {
                    parameters = new Object[1] {(Object) indent};
                    description = (string) mi.Invoke(obj, parameters);
                }
            }

            return description;
        }
#endif


        // 
        // Dumps an object to the debugger if the "Dump" tag is enabled,
        // or if the "Dump" tag is not present and the 'tag' is enabled.
        // 
        // @param tagName  The tag to Dump with.
        // @param obj  The object to dump.
        // 
        [System.Diagnostics.Conditional("DBG")]
        internal static void Dump(string tagName, Object obj) {
#if DBG
            EnsureInit();

            string  description;
            string  traceTag = null;
            bool    dumpEnabled, dumpPresent;

            if (obj != null) {
                dumpEnabled = IsTagEnabled("Dump");
                dumpPresent = IsTagPresent("Dump");
                if (dumpEnabled || !dumpPresent) {
                    if (IsTagEnabled(tagName)) {
                        traceTag = tagName;
                    }
                    else if (dumpEnabled) {
                        traceTag = "Dump";
                    }

                    if (traceTag != null) {
                        description = GetDescription(obj, string.Empty);
                        Debug.Trace(traceTag, "Dump\n" + description);
                    }
                }
            }
#endif
        }

#if DBG
        static internal string ToStringMaybeNull(object o) {
            if (o != null) {
                return o.ToString();
            }

            return "<null>";
        }
#endif

        static internal string FormatUtcDate(DateTime utcTime) {
#if DBG
            DateTime localTime = DateTimeUtil.ConvertToLocalTime(utcTime);
            return localTime.ToString(DATE_FORMAT, CultureInfo.InvariantCulture);
#else
            return string.Empty;
#endif
        }

        static internal string FormatLocalDate(DateTime localTime) {
#if DBG
            return localTime.ToString(DATE_FORMAT, CultureInfo.InvariantCulture);
#else
            return string.Empty;
#endif
        }
    }
}