/
console.cs
2304 lines (1982 loc) · 99 KB
/
console.cs
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.
//
// ==--==
/*=============================================================================
**
** Class: Console
**
**
** Purpose: This class provides access to the standard input, standard output
** and standard error streams.
**
**
=============================================================================*/
namespace System {
using System;
using System.IO;
using System.Text;
using System.Globalization;
using System.Security;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
// Provides static fields for console input & output. Use
// Console.In for input from the standard input stream (stdin),
// Console.Out for output to stdout, and Console.Error
// for output to stderr. If any of those console streams are
// redirected from the command line, these streams will be redirected.
// A program can also redirect its own output or input with the
// SetIn, SetOut, and SetError methods.
//
// The distinction between Console.Out & Console.Error is useful
// for programs that redirect output to a file or a pipe. Note that
// stdout & stderr can be output to different files at the same
// time from the DOS command line:
//
// someProgram 1> out 2> err
//
//Contains only static data. Serializable attribute not required.
public static class Console
{
private const int DefaultConsoleBufferSize = 256;
private const short AltVKCode = 0x12;
#if !FEATURE_PAL
private const int NumberLockVKCode = 0x90; // virtual key code
private const int CapsLockVKCode = 0x14;
// Beep range - see MSDN.
private const int MinBeepFrequency = 37;
private const int MaxBeepFrequency = 32767;
// MSDN says console titles can be up to 64 KB in length.
// But I get an exception if I use buffer lengths longer than
// ~24500 Unicode characters. Oh well.
private const int MaxConsoleTitleLength = 24500;
#endif // !FEATURE_PAL
#if !FEATURE_CORECLR
private static readonly UnicodeEncoding StdConUnicodeEncoding = new UnicodeEncoding(false, false);
#endif // !FEATURE_CORECLR
private static volatile TextReader _in;
private static volatile TextWriter _out;
private static volatile TextWriter _error;
private static volatile ConsoleCancelEventHandler _cancelCallbacks;
private static volatile ControlCHooker _hooker;
#if !FEATURE_PAL
// ReadLine & Read can't use this because they need to use ReadFile
// to be able to handle redirected input. We have to accept that
// we will lose repeated keystrokes when someone switches from
// calling ReadKey to calling Read or ReadLine. Those methods should
// ideally flush this cache as well.
[System.Security.SecurityCritical] // auto-generated
private static Win32Native.InputRecord _cachedInputRecord;
// For ResetColor
private static volatile bool _haveReadDefaultColors;
private static volatile byte _defaultColors;
#endif // !FEATURE_PAL
#if FEATURE_CODEPAGES_FILE // if no codepages file then locked into default
private static volatile bool _isOutTextWriterRedirected = false;
private static volatile bool _isErrorTextWriterRedirected = false;
#endif
private static volatile Encoding _inputEncoding = null;
private static volatile Encoding _outputEncoding = null;
#if !FEATURE_CORECLR
private static volatile bool _stdInRedirectQueried = false;
private static volatile bool _stdOutRedirectQueried = false;
private static volatile bool _stdErrRedirectQueried = false;
private static bool _isStdInRedirected;
private static bool _isStdOutRedirected;
private static bool _isStdErrRedirected;
#endif // !FEATURE_CORECLR
// Private object for locking instead of locking on a public type for SQL reliability work.
// Use this for internal synchronization during initialization, wiring up events, or for short, non-blocking OS calls.
private static volatile Object s_InternalSyncObject;
private static Object InternalSyncObject {
get {
Contract.Ensures(Contract.Result<Object>() != null);
if (s_InternalSyncObject == null) {
Object o = new Object();
#pragma warning disable 0420
Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
#pragma warning restore 0420
}
return s_InternalSyncObject;
}
}
// Use this for blocking in Console.ReadKey, which needs to protect itself in case multiple threads call it simultaneously.
// Use a ReadKey-specific lock though, to allow other fields to be initialized on this type.
private static volatile Object s_ReadKeySyncObject;
private static Object ReadKeySyncObject
{
get
{
Contract.Ensures(Contract.Result<Object>() != null);
if (s_ReadKeySyncObject == null)
{
Object o = new Object();
#pragma warning disable 0420
Interlocked.CompareExchange<Object>(ref s_ReadKeySyncObject, o, null);
#pragma warning restore 0420
}
return s_ReadKeySyncObject;
}
}
// About reliability: I'm not using SafeHandle here. We don't
// need to close these handles, and we don't allow the user to close
// them so we don't have many of the security problems inherent in
// something like file handles. Additionally, in a host like SQL
// Server, we won't have a console.
private static volatile IntPtr _consoleInputHandle;
private static volatile IntPtr _consoleOutputHandle;
private static IntPtr ConsoleInputHandle {
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
get {
if (_consoleInputHandle == IntPtr.Zero) {
_consoleInputHandle = Win32Native.GetStdHandle(Win32Native.STD_INPUT_HANDLE);
}
return _consoleInputHandle;
}
}
private static IntPtr ConsoleOutputHandle {
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
get {
if (_consoleOutputHandle == IntPtr.Zero) {
_consoleOutputHandle = Win32Native.GetStdHandle(Win32Native.STD_OUTPUT_HANDLE);
}
return _consoleOutputHandle;
}
}
#if !FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
private static bool IsHandleRedirected(IntPtr ioHandle) {
// Need this to use GetFileType:
SafeFileHandle safeIOHandle = new SafeFileHandle(ioHandle, false);
// If handle is not to a character device, we must be redirected:
int fileType = Win32Native.GetFileType(safeIOHandle);
if ((fileType & Win32Native.FILE_TYPE_CHAR) != Win32Native.FILE_TYPE_CHAR)
return true;
// We are on a char device.
// If GetConsoleMode succeeds, we are NOT redirected.
int mode;
bool success = Win32Native.GetConsoleMode(ioHandle, out mode);
return !success;
}
public static bool IsInputRedirected {
[System.Security.SecuritySafeCritical]
get {
if (_stdInRedirectQueried)
return _isStdInRedirected;
lock (InternalSyncObject) {
if (_stdInRedirectQueried)
return _isStdInRedirected;
_isStdInRedirected = IsHandleRedirected(ConsoleInputHandle);
_stdInRedirectQueried = true;
return _isStdInRedirected;
}
}
} // public static bool IsInputRedirected
public static bool IsOutputRedirected {
[System.Security.SecuritySafeCritical]
get {
if (_stdOutRedirectQueried)
return _isStdOutRedirected;
lock (InternalSyncObject) {
if (_stdOutRedirectQueried)
return _isStdOutRedirected;
_isStdOutRedirected = IsHandleRedirected(ConsoleOutputHandle);
_stdOutRedirectQueried = true;
return _isStdOutRedirected;
}
}
} // public static bool IsOutputRedirected
public static bool IsErrorRedirected {
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
get {
if (_stdErrRedirectQueried)
return _isStdErrRedirected;
lock (InternalSyncObject) {
if (_stdErrRedirectQueried)
return _isStdErrRedirected;
IntPtr errHndle = Win32Native.GetStdHandle(Win32Native.STD_ERROR_HANDLE);
_isStdErrRedirected = IsHandleRedirected(errHndle);
_stdErrRedirectQueried = true;
return _isStdErrRedirected;
}
}
} // public static bool IsErrorRedirected
#endif // !FEATURE_CORECLR
public static TextReader In {
[System.Security.SecuritySafeCritical] // auto-generated
[HostProtection(UI=true)]
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
get {
Contract.Ensures(Contract.Result<TextReader>() != null);
// Because most applications don't use stdin, we can delay
// initialize it slightly better startup performance.
if (_in == null) {
lock(InternalSyncObject) {
if (_in == null) {
// Set up Console.In
Stream s = OpenStandardInput(DefaultConsoleBufferSize);
TextReader tr;
if (s == Stream.Null)
tr = StreamReader.Null;
else {
// Hopefully Encoding.GetEncoding doesn't load as many classes now.
#if FEATURE_CORECLR
Encoding enc = Encoding.UTF8;
#else // FEATURE_CORECLR
Encoding enc = InputEncoding;
#endif // FEATURE_CORECLR
tr = TextReader.Synchronized(new StreamReader(s, enc, false, DefaultConsoleBufferSize, true));
}
System.Threading.Thread.MemoryBarrier();
_in = tr;
}
}
}
return _in;
}
}
public static TextWriter Out {
[HostProtection(UI=true)]
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
get {
Contract.Ensures(Contract.Result<TextWriter>() != null);
// Hopefully this is inlineable.
if (_out == null)
InitializeStdOutError(true);
return _out;
}
}
public static TextWriter Error {
[HostProtection(UI=true)]
get {
Contract.Ensures(Contract.Result<TextWriter>() != null);
// Hopefully this is inlineable.
if (_error == null)
InitializeStdOutError(false);
return _error;
}
}
// For console apps, the console handles are set to values like 3, 7,
// and 11 OR if you've been created via CreateProcess, possibly -1
// or 0. -1 is definitely invalid, while 0 is probably invalid.
// Also note each handle can independently be invalid or good.
// For Windows apps, the console handles are set to values like 3, 7,
// and 11 but are invalid handles - you may not write to them. However,
// you can still spawn a Windows app via CreateProcess and read stdout
// and stderr.
// So, we always need to check each handle independently for validity
// by trying to write or read to it, unless it is -1.
// We do not do a security check here, under the assumption that this
// cannot create a security hole, but only waste a user's time or
// cause a possible denial of service attack.
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
private static void InitializeStdOutError(bool stdout)
{
// Set up Console.Out or Console.Error.
lock(InternalSyncObject) {
if (stdout && _out != null)
return;
else if (!stdout && _error != null)
return;
TextWriter writer = null;
Stream s;
if (stdout)
s = OpenStandardOutput(DefaultConsoleBufferSize);
else
s = OpenStandardError(DefaultConsoleBufferSize);
if (s == Stream.Null) {
#if _DEBUG
if (CheckOutputDebug())
writer = MakeDebugOutputTextWriter((stdout) ? "Console.Out: " : "Console.Error: ");
else
#endif // _DEBUG
writer = TextWriter.Synchronized(StreamWriter.Null);
}
else {
#if FEATURE_CORECLR
Encoding encoding = Encoding.UTF8;
#else // FEATURE_CORECLR
Encoding encoding = OutputEncoding;
#endif // FEATURE_CORECLR
StreamWriter stdxxx = new StreamWriter(s, encoding, DefaultConsoleBufferSize, true);
stdxxx.HaveWrittenPreamble = true;
stdxxx.AutoFlush = true;
writer = TextWriter.Synchronized(stdxxx);
}
if (stdout)
_out = writer;
else
_error = writer;
Contract.Assert((stdout && _out != null) || (!stdout && _error != null), "Didn't set Console::_out or _error appropriately!");
}
}
// This is ONLY used in debug builds. If you have a registry key set,
// it will redirect Console.Out & Error on console-less applications to
// your debugger's output window.
#if _DEBUG
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private static bool CheckOutputDebug()
{
#if FEATURE_WIN32_REGISTRY
new System.Security.Permissions.RegistryPermission(RegistryPermissionAccess.Read | RegistryPermissionAccess.Write, "HKEY_LOCAL_MACHINE").Assert();
RegistryKey rk = Registry.LocalMachine;
using (rk = rk.OpenSubKey("Software\\Microsoft\\.NETFramework", false)) {
if (rk != null) {
Object obj = rk.GetValue("ConsoleSpewToDebugger", 0);
if (obj != null && ((int)obj) != 0) {
return true;
}
}
}
return false;
#else // FEATURE_WIN32_REGISTRY
#if FEATURE_PAL && !FEATURE_CORECLR
const int parameterValueLength = 255;
StringBuilder parameterValue = new StringBuilder(parameterValueLength);
bool rc = Win32Native.FetchConfigurationString(true, "ConsoleSpewToDebugger", parameterValue, parameterValueLength);
if (rc) {
if (0 != parameterValue.Length) {
int value = Convert.ToInt32(parameterValue.ToString());
if (0 != value)
return true;
}
}
#endif // FEATURE_PAL && !FEATURE_CORECLR
return false;
#endif // FEATURE_WIN32_REGISTRY
}
#endif // _DEBUG
#if _DEBUG
private static TextWriter MakeDebugOutputTextWriter(String streamLabel)
{
TextWriter output = new __DebugOutputTextWriter(streamLabel);
output.WriteLine("Output redirected to debugger from a bit bucket.");
return TextWriter.Synchronized(output);
}
#endif // _DEBUG
#if !FEATURE_CORECLR
// We cannot simply compare the encoding to Encoding.Unicode bacasue it incorporates BOM
// and we do not care about BOM. Instead, we compare by class, codepage and little-endianess only:
private static bool IsStandardConsoleUnicodeEncoding(Encoding encoding) {
UnicodeEncoding enc = encoding as UnicodeEncoding;
if (null == enc)
return false;
return (StdConUnicodeEncoding.CodePage == enc.CodePage)
&& (StdConUnicodeEncoding.bigEndian == enc.bigEndian);
}
private static bool GetUseFileAPIs(int handleType) {
switch(handleType) {
case Win32Native.STD_INPUT_HANDLE:
return !IsStandardConsoleUnicodeEncoding(InputEncoding) || IsInputRedirected;
case Win32Native.STD_OUTPUT_HANDLE:
return !IsStandardConsoleUnicodeEncoding(OutputEncoding) || IsOutputRedirected;
case Win32Native.STD_ERROR_HANDLE:
return !IsStandardConsoleUnicodeEncoding(OutputEncoding) || IsErrorRedirected;
default:
// This can never happen.
Contract.Assert(false, "Unexpected handleType value (" + handleType + ")");
return true;
}
}
#endif // !FEATURE_CORECLR
// This method is only exposed via methods to get at the console.
// We won't use any security checks here.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
private static Stream GetStandardFile(int stdHandleName, FileAccess access, int bufferSize) {
// We shouldn't close the handle for stdout, etc, or we'll break
// unmanaged code in the process that will print to console.
// We should have a better way of marking this on SafeHandle.
IntPtr handle = Win32Native.GetStdHandle(stdHandleName);
SafeFileHandle sh = new SafeFileHandle(handle, false);
// If someone launches a managed process via CreateProcess, stdout
// stderr, & stdin could independently be set to INVALID_HANDLE_VALUE.
// Additionally they might use 0 as an invalid handle.
if (sh.IsInvalid) {
// Minor perf optimization - get it out of the finalizer queue.
sh.SetHandleAsInvalid();
return Stream.Null;
}
// Check whether we can read or write to this handle.
if (stdHandleName != Win32Native.STD_INPUT_HANDLE && !ConsoleHandleIsWritable(sh)) {
//BCLDebug.ConsoleError("Console::ConsoleHandleIsValid for std handle "+stdHandleName+" failed, setting it to a null stream");
return Stream.Null;
}
#if !FEATURE_CORECLR
bool useFileAPIs = GetUseFileAPIs(stdHandleName);
#else
const bool useFileAPIs = true;
#endif // !FEATURE_CORECLR
//BCLDebug.ConsoleError("Console::GetStandardFile for std handle "+stdHandleName+" succeeded, returning handle number "+handle.ToString());
Stream console = new __ConsoleStream(sh, access, useFileAPIs);
// Do not buffer console streams, or we can get into situations where
// we end up blocking waiting for you to hit enter twice. It was
// redundant.
return console;
}
// Checks whether stdout or stderr are writable. Do NOT pass
// stdin here.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
private static unsafe bool ConsoleHandleIsWritable(SafeFileHandle outErrHandle) {
// Do NOT call this method on stdin!
// Windows apps may have non-null valid looking handle values for
// stdin, stdout and stderr, but they may not be readable or
// writable. Verify this by calling WriteFile in the
// appropriate modes.
// This must handle console-less Windows apps.
int bytesWritten;
byte junkByte = 0x41;
int r = Win32Native.WriteFile(outErrHandle, &junkByte, 0, out bytesWritten, IntPtr.Zero);
// In Win32 apps w/ no console, bResult should be 0 for failure.
return r != 0;
}
public static Encoding InputEncoding {
[System.Security.SecuritySafeCritical] // auto-generated
get {
Contract.Ensures(Contract.Result<Encoding>() != null);
if (null != _inputEncoding)
return _inputEncoding;
lock(InternalSyncObject) {
if (null != _inputEncoding)
return _inputEncoding;
uint cp = Win32Native.GetConsoleCP();
_inputEncoding = Encoding.GetEncoding((int) cp);
return _inputEncoding;
}
}
#if FEATURE_CODEPAGES_FILE // if no codepages file then locked into default
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
set {
if (value == null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
new UIPermission(UIPermissionWindow.SafeTopLevelWindows).Demand();
lock(InternalSyncObject) {
if (!IsStandardConsoleUnicodeEncoding(value)) {
uint cp = (uint) value.CodePage;
bool r = Win32Native.SetConsoleCP(cp);
if (!r)
__Error.WinIOError();
}
_inputEncoding = (Encoding) value.Clone();
// We need to reinitialize Console.In in the next call to _in
// This will discard the current StreamReader, potentially
// losing buffered data
_in = null;
}
} // set
#endif // FEATURE_CODEPAGES_FILE
} // public static Encoding InputEncoding
public static Encoding OutputEncoding {
[System.Security.SecuritySafeCritical] // auto-generated
get {
Contract.Ensures(Contract.Result<Encoding>() != null);
if (null != _outputEncoding)
return _outputEncoding;
lock(InternalSyncObject) {
if (null != _outputEncoding)
return _outputEncoding;
uint cp = Win32Native.GetConsoleOutputCP();
_outputEncoding = Encoding.GetEncoding((int) cp);
return _outputEncoding;
}
}
#if FEATURE_CODEPAGES_FILE // if no codepages file then locked into default
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
set {
if (value == null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
new UIPermission(UIPermissionWindow.SafeTopLevelWindows).Demand();
lock(InternalSyncObject) {
// Before changing the code page we need to flush the data
// if Out hasn't been redirected. Also, have the next call to
// _out reinitialize the console code page.
if (_out != null && !_isOutTextWriterRedirected) {
_out.Flush();
_out = null;
}
if (_error != null && !_isErrorTextWriterRedirected) {
_error.Flush();
_error = null;
}
if (!IsStandardConsoleUnicodeEncoding(value)) {
uint cp = (uint) value.CodePage;
bool r = Win32Native.SetConsoleOutputCP(cp);
if (!r)
__Error.WinIOError();
}
_outputEncoding = (Encoding) value.Clone();
}
} // set
#endif // FEATURE_CODEPAGES_FILE
} // public static Encoding OutputEncoding
#if !FEATURE_PAL
[HostProtection(UI=true)]
public static void Beep()
{
Beep(800, 200);
}
[System.Security.SecuritySafeCritical] // auto-generated
[HostProtection(UI=true)]
public static void Beep(int frequency, int duration)
{
if (frequency < MinBeepFrequency || frequency > MaxBeepFrequency)
throw new ArgumentOutOfRangeException("frequency", frequency, Environment.GetResourceString("ArgumentOutOfRange_BeepFrequency", MinBeepFrequency, MaxBeepFrequency));
if (duration <= 0)
throw new ArgumentOutOfRangeException("duration", duration, Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
// Note that Beep over Remote Desktop connections does not currently
Contract.EndContractBlock();
// work. Ignore any failures here.
Win32Native.Beep(frequency, duration);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static void Clear()
{
Win32Native.COORD coordScreen = new Win32Native.COORD();
Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi;
bool success;
int conSize;
IntPtr hConsole = ConsoleOutputHandle;
if (hConsole == Win32Native.INVALID_HANDLE_VALUE)
throw new IOException(Environment.GetResourceString("IO.IO_NoConsole"));
// get the number of character cells in the current buffer
// Go through my helper method for fetching a screen buffer info
// to correctly handle default console colors.
csbi = GetBufferInfo();
conSize = csbi.dwSize.X * csbi.dwSize.Y;
// fill the entire screen with blanks
int numCellsWritten = 0;
success = Win32Native.FillConsoleOutputCharacter(hConsole, ' ',
conSize, coordScreen, out numCellsWritten);
if (!success)
__Error.WinIOError();
// now set the buffer's attributes accordingly
numCellsWritten = 0;
success = Win32Native.FillConsoleOutputAttribute(hConsole, csbi.wAttributes,
conSize, coordScreen, out numCellsWritten);
if (!success)
__Error.WinIOError();
// put the cursor at (0, 0)
success = Win32Native.SetConsoleCursorPosition(hConsole, coordScreen);
if (!success)
__Error.WinIOError();
}
[System.Security.SecurityCritical] // auto-generated
private static Win32Native.Color ConsoleColorToColorAttribute(ConsoleColor color, bool isBackground)
{
if ((((int)color) & ~0xf) != 0)
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidConsoleColor"));
Contract.EndContractBlock();
Win32Native.Color c = (Win32Native.Color) color;
// Make these background colors instead of foreground
if (isBackground)
c = (Win32Native.Color) ((int)c << 4);
return c;
}
[System.Security.SecurityCritical] // auto-generated
private static ConsoleColor ColorAttributeToConsoleColor(Win32Native.Color c)
{
// Turn background colors into foreground colors.
if ((c & Win32Native.Color.BackgroundMask) != 0)
c = (Win32Native.Color) (((int)c) >> 4);
return (ConsoleColor) c;
}
public static ConsoleColor BackgroundColor {
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
get {
bool succeeded;
Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded);
// For code that may be used from Windows app w/ no console
if (!succeeded)
return ConsoleColor.Black;
Win32Native.Color c = (Win32Native.Color) csbi.wAttributes & Win32Native.Color.BackgroundMask;
return ColorAttributeToConsoleColor(c);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
set {
new UIPermission(UIPermissionWindow.SafeTopLevelWindows).Demand();
Win32Native.Color c = ConsoleColorToColorAttribute(value, true);
bool succeeded;
Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded);
// For code that may be used from Windows app w/ no console
if (!succeeded)
return;
Contract.Assert(_haveReadDefaultColors, "Setting the foreground color before we've read the default foreground color!");
short attrs = csbi.wAttributes;
attrs &= ~((short)Win32Native.Color.BackgroundMask);
// C#'s bitwise-or sign-extends to 32 bits.
attrs = (short) (((uint) (ushort) attrs) | ((uint) (ushort) c));
// Ignore errors here - there are some scenarios for running code that wants
// to print in colors to the console in a Windows application.
Win32Native.SetConsoleTextAttribute(ConsoleOutputHandle, attrs);
}
} // public static ConsoleColor BackgroundColor
public static ConsoleColor ForegroundColor {
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
get {
bool succeeded;
Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded);
// For code that may be used from Windows app w/ no console
if (!succeeded)
return ConsoleColor.Gray;
Win32Native.Color c = (Win32Native.Color) csbi.wAttributes & Win32Native.Color.ForegroundMask;
return ColorAttributeToConsoleColor(c);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
set {
new UIPermission(UIPermissionWindow.SafeTopLevelWindows).Demand();
Win32Native.Color c = ConsoleColorToColorAttribute(value, false);
bool succeeded;
Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded);
// For code that may be used from Windows app w/ no console
if (!succeeded)
return;
Contract.Assert(_haveReadDefaultColors, "Setting the foreground color before we've read the default foreground color!");
short attrs = csbi.wAttributes;
attrs &= ~((short)Win32Native.Color.ForegroundMask);
// C#'s bitwise-or sign-extends to 32 bits.
attrs = (short) (((uint) (ushort) attrs) | ((uint) (ushort) c));
// Ignore errors here - there are some scenarios for running code that wants
// to print in colors to the console in a Windows application.
Win32Native.SetConsoleTextAttribute(ConsoleOutputHandle, attrs);
}
} // public static ConsoleColor ForegroundColor
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static void ResetColor()
{
new UIPermission(UIPermissionWindow.SafeTopLevelWindows).Demand();
bool succeeded;
Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo(false, out succeeded);
// For code that may be used from Windows app w/ no console
if (!succeeded)
return;
Contract.Assert(_haveReadDefaultColors, "Setting the foreground color before we've read the default foreground color!");
short defaultAttrs = (short) (ushort) _defaultColors;
// Ignore errors here - there are some scenarios for running code that wants
// to print in colors to the console in a Windows application.
Win32Native.SetConsoleTextAttribute(ConsoleOutputHandle, defaultAttrs);
}
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public static void MoveBufferArea(int sourceLeft, int sourceTop,
int sourceWidth, int sourceHeight, int targetLeft, int targetTop)
{
MoveBufferArea(sourceLeft, sourceTop, sourceWidth, sourceHeight, targetLeft, targetTop, ' ', ConsoleColor.Black, BackgroundColor);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public unsafe static void MoveBufferArea(int sourceLeft, int sourceTop,
int sourceWidth, int sourceHeight, int targetLeft, int targetTop,
char sourceChar, ConsoleColor sourceForeColor,
ConsoleColor sourceBackColor)
{
if (sourceForeColor < ConsoleColor.Black || sourceForeColor > ConsoleColor.White)
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidConsoleColor"), "sourceForeColor");
if (sourceBackColor < ConsoleColor.Black || sourceBackColor > ConsoleColor.White)
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidConsoleColor"), "sourceBackColor");
Contract.EndContractBlock();
Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
Win32Native.COORD bufferSize = csbi.dwSize;
if (sourceLeft < 0 || sourceLeft > bufferSize.X)
throw new ArgumentOutOfRangeException("sourceLeft", sourceLeft, Environment.GetResourceString("ArgumentOutOfRange_ConsoleBufferBoundaries"));
if (sourceTop < 0 || sourceTop > bufferSize.Y)
throw new ArgumentOutOfRangeException("sourceTop", sourceTop, Environment.GetResourceString("ArgumentOutOfRange_ConsoleBufferBoundaries"));
if (sourceWidth < 0 || sourceWidth > bufferSize.X - sourceLeft)
throw new ArgumentOutOfRangeException("sourceWidth", sourceWidth, Environment.GetResourceString("ArgumentOutOfRange_ConsoleBufferBoundaries"));
if (sourceHeight < 0 || sourceTop > bufferSize.Y - sourceHeight)
throw new ArgumentOutOfRangeException("sourceHeight", sourceHeight, Environment.GetResourceString("ArgumentOutOfRange_ConsoleBufferBoundaries"));
// Note: if the target range is partially in and partially out
// of the buffer, then we let the OS clip it for us.
if (targetLeft < 0 || targetLeft > bufferSize.X)
throw new ArgumentOutOfRangeException("targetLeft", targetLeft, Environment.GetResourceString("ArgumentOutOfRange_ConsoleBufferBoundaries"));
if (targetTop < 0 || targetTop > bufferSize.Y)
throw new ArgumentOutOfRangeException("targetTop", targetTop, Environment.GetResourceString("ArgumentOutOfRange_ConsoleBufferBoundaries"));
// If we're not doing any work, bail out now (Windows will return
// an error otherwise)
if (sourceWidth == 0 || sourceHeight == 0)
return;
new UIPermission(UIPermissionWindow.SafeTopLevelWindows).Demand();
// Read data from the original location, blank it out, then write
// it to the new location. This will handle overlapping source and
// destination regions correctly.
// See the "Reading and Writing Blocks of Characters and Attributes"
// sample for help
// Read the old data
Win32Native.CHAR_INFO[] data = new Win32Native.CHAR_INFO[sourceWidth * sourceHeight];
bufferSize.X = (short) sourceWidth;
bufferSize.Y = (short) sourceHeight;
Win32Native.COORD bufferCoord = new Win32Native.COORD();
Win32Native.SMALL_RECT readRegion = new Win32Native.SMALL_RECT();
readRegion.Left = (short) sourceLeft;
readRegion.Right = (short) (sourceLeft + sourceWidth - 1);
readRegion.Top = (short) sourceTop;
readRegion.Bottom = (short) (sourceTop + sourceHeight - 1);
bool r;
fixed(Win32Native.CHAR_INFO* pCharInfo = data)
r = Win32Native.ReadConsoleOutput(ConsoleOutputHandle, pCharInfo, bufferSize, bufferCoord, ref readRegion);
if (!r)
__Error.WinIOError();
// Overwrite old section
// I don't have a good function to blank out a rectangle.
Win32Native.COORD writeCoord = new Win32Native.COORD();
writeCoord.X = (short) sourceLeft;
Win32Native.Color c = ConsoleColorToColorAttribute(sourceBackColor, true);
c |= ConsoleColorToColorAttribute(sourceForeColor, false);
short attr = (short) c;
int numWritten;
for(int i = sourceTop; i<sourceTop + sourceHeight; i++) {
writeCoord.Y = (short) i;
r = Win32Native.FillConsoleOutputCharacter(ConsoleOutputHandle, sourceChar, sourceWidth, writeCoord, out numWritten);
Contract.Assert(numWritten == sourceWidth, "FillConsoleOutputCharacter wrote the wrong number of chars!");
if (!r)
__Error.WinIOError();
r = Win32Native.FillConsoleOutputAttribute(ConsoleOutputHandle, attr, sourceWidth, writeCoord, out numWritten);
if (!r)
__Error.WinIOError();
}
// Write text to new location
Win32Native.SMALL_RECT writeRegion = new Win32Native.SMALL_RECT();
writeRegion.Left = (short) targetLeft;
writeRegion.Right = (short) (targetLeft + sourceWidth);
writeRegion.Top = (short) targetTop;
writeRegion.Bottom = (short) (targetTop + sourceHeight);
fixed(Win32Native.CHAR_INFO* pCharInfo = data)
r = Win32Native.WriteConsoleOutput(ConsoleOutputHandle, pCharInfo, bufferSize, bufferCoord, ref writeRegion);
} // MoveBufferArea
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
private static Win32Native.CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo()
{
bool junk;
return GetBufferInfo(true, out junk);
}
// For apps that don't have a console (like Windows apps), they might
// run other code that includes color console output. Allow a mechanism
// where that code won't throw an exception for simple errors.
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
private static Win32Native.CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo(bool throwOnNoConsole, out bool succeeded)
{
succeeded = false;
Win32Native.CONSOLE_SCREEN_BUFFER_INFO csbi;
bool success;
IntPtr hConsole = ConsoleOutputHandle;
if (hConsole == Win32Native.INVALID_HANDLE_VALUE) {
if (!throwOnNoConsole)
return new Win32Native.CONSOLE_SCREEN_BUFFER_INFO();
else
throw new IOException(Environment.GetResourceString("IO.IO_NoConsole"));
}
// Note that if stdout is redirected to a file, the console handle
// may be a file. If this fails, try stderr and stdin.
success = Win32Native.GetConsoleScreenBufferInfo(hConsole, out csbi);
if (!success) {
success = Win32Native.GetConsoleScreenBufferInfo(Win32Native.GetStdHandle(Win32Native.STD_ERROR_HANDLE), out csbi);
if (!success)
success = Win32Native.GetConsoleScreenBufferInfo(Win32Native.GetStdHandle(Win32Native.STD_INPUT_HANDLE), out csbi);
if (!success) {
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Win32Native.ERROR_INVALID_HANDLE && !throwOnNoConsole)
return new Win32Native.CONSOLE_SCREEN_BUFFER_INFO();
__Error.WinIOError(errorCode, null);
}
}
if (!_haveReadDefaultColors) {
// Fetch the default foreground and background color for the
// ResetColor method.
Contract.Assert((int)Win32Native.Color.ColorMask == 0xff, "Make sure one byte is large enough to store a Console color value!");
_defaultColors = (byte) (csbi.wAttributes & (short) Win32Native.Color.ColorMask);
_haveReadDefaultColors = true;
}
succeeded = true;