forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClrFacade.cs
More file actions
887 lines (797 loc) · 35.1 KB
/
ClrFacade.cs
File metadata and controls
887 lines (797 loc) · 35.1 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
//
// Copyright (C) Microsoft. All rights reserved.
//
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation.Language;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Security;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices.ComTypes;
#if CORECLR
using System.Runtime.Loader; /* used in facade APIs related to assembly operations */
using System.Management.Automation.Host; /* used in facade API 'GetUninitializedObject' */
using Microsoft.PowerShell.CoreClr.Stubs; /* used in facade API 'GetFileSecurityZone' */
using System.Management.Automation.Internal;
using System.Text.RegularExpressions;
#else
using System.Runtime.Serialization; /* used in facade API 'GetUninitializedObject' */
#endif
namespace System.Management.Automation
{
/// <summary>
/// ClrFacade contains all diverging code (different implementation for FullCLR and CoreCLR using if/def).
/// It exposes common APIs that can be used by the rest of the code base.
/// </summary>
internal static class ClrFacade
{
/// <summary>
/// We need it to avoid calling lookups inside dynamic assemblies with PS Types, so we exclude it from GetAssemblies().
/// We use this convention for names to archive it.
/// </summary>
internal static readonly char FIRST_CHAR_PSASSEMBLY_MARK = (char)0x29f9;
#region Process
/// <summary>
/// Facade for ProcessModule FileVersionInfo
/// </summary>
/// <param name="processModule"></param>
/// <returns>FileVersionInfo</returns>
internal static FileVersionInfo GetProcessModuleFileVersionInfo(ProcessModule processModule)
{
#if CORECLR
return FileVersionInfo.GetVersionInfo(processModule.FileName);
#else
return processModule.FileVersionInfo;
#endif
}
/// <summary>
/// Facade for Process.Handle to get SafeHandle
/// </summary>
/// <param name="process"></param>
/// <returns>SafeHandle</returns>
internal static SafeHandle GetSafeProcessHandle(Process process)
{
#if CORECLR
return process.SafeHandle;
#else
return new SafeProcessHandle(process.Handle);
#endif
}
/// <summary>
/// Facade for Process.Handle to get raw handle
/// </summary>
internal static IntPtr GetRawProcessHandle(Process process)
{
#if CORECLR
try
{
return process.SafeHandle.DangerousGetHandle();
}
catch (InvalidOperationException)
{
// It's possible that the process has already exited when we try to get its handle.
// In that case, InvalidOperationException will be thrown from Process.SafeHandle,
// and we return the invalid zero pointer.
return IntPtr.Zero;
}
#else
return process.Handle;
#endif
}
#if CORECLR
/// <summary>
/// Facade for ProcessStartInfo.Environment
/// </summary>
internal static IDictionary<string, string> GetProcessEnvironment(ProcessStartInfo startInfo)
{
return startInfo.Environment;
}
#else
/// <summary>
/// Facade for ProcessStartInfo.EnvironmentVariables
/// </summary>
internal static System.Collections.Specialized.StringDictionary GetProcessEnvironment(ProcessStartInfo startInfo)
{
return startInfo.EnvironmentVariables;
}
#endif
#endregion Process
#region Marshal
/// <summary>
/// Facade for Marshal.SizeOf
/// </summary>
internal static int SizeOf<T>()
{
#if CORECLR
// Marshal.SizeOf(Type) is obsolete in CoreCLR
return Marshal.SizeOf<T>();
#else
return Marshal.SizeOf(typeof(T));
#endif
}
/// <summary>
/// Facade for Marshal.DestroyStructure
/// </summary>
internal static void DestroyStructure<T>(IntPtr ptr)
{
#if CORECLR
// Marshal.DestroyStructure(IntPtr, Type) is obsolete in CoreCLR
Marshal.DestroyStructure<T>(ptr);
#else
Marshal.DestroyStructure(ptr, typeof(T));
#endif
}
/// <summary>
/// Facade for Marshal.PtrToStructure
/// </summary>
internal static T PtrToStructure<T>(IntPtr ptr)
{
#if CORECLR
// Marshal.PtrToStructure(IntPtr, Type) is obsolete in CoreCLR
return Marshal.PtrToStructure<T>(ptr);
#else
return (T)Marshal.PtrToStructure(ptr, typeof(T));
#endif
}
/// <summary>
/// Wraps Marshal.StructureToPtr to hide differences between the CLRs.
/// </summary>
internal static void StructureToPtr<T>(
T structure,
IntPtr ptr,
bool deleteOld)
{
#if CORECLR
Marshal.StructureToPtr<T>(structure, ptr, deleteOld);
#else
Marshal.StructureToPtr(structure, ptr, deleteOld);
#endif
}
/// <summary>
/// Facade for SecureStringToCoTaskMemUnicode
/// </summary>
internal static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
{
#if CORECLR
return SecureStringMarshal.SecureStringToCoTaskMemUnicode(s);
#else
return Marshal.SecureStringToCoTaskMemUnicode(s);
#endif
}
#endregion Marshal
#region Assembly
/// <summary>
/// Facade for AssemblyName.GetAssemblyName(string)
/// </summary>
internal static AssemblyName GetAssemblyName(string assemblyPath)
{
#if CORECLR // AssemblyName.GetAssemblyName(assemblyPath) is not in CoreCLR
return AssemblyLoadContext.GetAssemblyName(assemblyPath);
#else
return AssemblyName.GetAssemblyName(assemblyPath);
#endif
}
internal static IEnumerable<Assembly> GetAssemblies(TypeResolutionState typeResolutionState, TypeName typeName)
{
#if CORECLR
string typeNameToSearch = typeResolutionState.GetAlternateTypeName(typeName.Name) ?? typeName.Name;
return GetAssemblies(typeNameToSearch);
#else
return GetAssemblies();
#endif
}
/// <summary>
/// Facade for AppDomain.GetAssemblies
/// </summary>
/// <param name="namespaceQualifiedTypeName">
/// In CoreCLR context, if it's for string-to-type conversion and the namespace qualified type name is known, pass it in so that
/// powershell can load the necessary TPA if the target type is from an unloaded TPA.
/// </param>
internal static IEnumerable<Assembly> GetAssemblies(string namespaceQualifiedTypeName = null)
{
#if CORECLR
return PSAssemblyLoadContext.GetAssemblies(namespaceQualifiedTypeName);
#else
return AppDomain.CurrentDomain.GetAssemblies().Where(a => !(a.FullName.Length > 0 && a.FullName[0] == FIRST_CHAR_PSASSEMBLY_MARK));
#endif
}
/// <summary>
/// Facade for Assembly.LoadFrom
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")]
internal static Assembly LoadFrom(string assemblyPath)
{
#if CORECLR
return PSAssemblyLoadContext.LoadFrom(assemblyPath);
#else
return Assembly.LoadFrom(assemblyPath);
#endif
}
/// <summary>
/// Facade for EnumBuilder.CreateTypeInfo
/// </summary>
/// <remarks>
/// In Core PowerShell, we need to track the dynamic assemblies that powershell generates.
/// </remarks>
internal static void CreateEnumType(EnumBuilder enumBuilder)
{
#if CORECLR
// Create the enum type and add the dynamic assembly to assembly cache.
TypeInfo enumTypeinfo = enumBuilder.CreateTypeInfo();
PSAssemblyLoadContext.TryAddAssemblyToCache(enumTypeinfo.Assembly);
#else
enumBuilder.CreateTypeInfo();
#endif
}
#if CORECLR
/// <summary>
/// Probe (look for) the assembly file with the specified short name.
/// </summary>
/// <remarks>
/// In Core PowerShell, we need to analyze the metadata of assembly files for binary modules. Sometimes we
/// need to find an assembly file that is referenced by the assembly file that is being processed. To find
/// the reference assembly file, we need to probe the PSBase and the additional searching path if it's specified.
/// </remarks>
internal static string ProbeAssemblyPath(string assemblyShortName, string additionalSearchPath = null)
{
if (string.IsNullOrWhiteSpace(assemblyShortName))
{
throw new ArgumentNullException("assemblyShortName");
}
return PSAssemblyLoadContext.ProbeAssemblyFileForMetadataAnalysis(assemblyShortName, additionalSearchPath);
}
/// <summary>
/// Get the namespace-qualified type names of all available CoreCLR .NET types.
/// This is used for type name auto-completion in PS engine.
/// </summary>
internal static IEnumerable<string> GetAvailableCoreClrDotNetTypes()
{
return PSAssemblyLoadContext.GetAvailableDotNetTypes();
}
/// <summary>
/// Load assembly from byte stream.
/// </summary>
internal static Assembly LoadFrom(Stream assembly)
{
return PSAssemblyLoadContext.LoadFrom(assembly);
}
/// <summary>
/// Add the AssemblyLoad handler
/// </summary>
internal static void AddAssemblyLoadHandler(Action<Assembly> handler)
{
PSAssemblyLoadContext.AssemblyLoad += handler;
}
private static PowerShellAssemblyLoadContext PSAssemblyLoadContext
{
get
{
if (PowerShellAssemblyLoadContext.Instance == null)
{
throw new InvalidOperationException(ParserStrings.LoadContextNotInitialized);
}
return PowerShellAssemblyLoadContext.Instance;
}
}
#endif
/// <summary>
/// Facade for Assembly.GetCustomAttributes
/// </summary>
internal static object[] GetCustomAttributes<T>(Assembly assembly)
{
#if CORECLR // Assembly.GetCustomAttributes(Type, Boolean) is not in CORE CLR
return assembly.GetCustomAttributes(typeof(T)).ToArray();
#else
return assembly.GetCustomAttributes(typeof(T), false);
#endif
}
#endregion Assembly
#region Encoding
/// <summary>
/// Facade for getting default encoding
/// </summary>
internal static Encoding GetDefaultEncoding()
{
if (s_defaultEncoding == null)
{
#if UNIX // PowerShell Core on Unix
s_defaultEncoding = new UTF8Encoding(false);
#elif CORECLR // PowerShell Core on Windows
EncodingRegisterProvider();
uint currentAnsiCp = NativeMethods.GetACP();
s_defaultEncoding = Encoding.GetEncoding((int)currentAnsiCp);
#else // Windows PowerShell
s_defaultEncoding = Encoding.Default;
#endif
}
return s_defaultEncoding;
}
private static volatile Encoding s_defaultEncoding;
/// <summary>
/// Facade for getting OEM encoding
/// </summary>
internal static Encoding GetOEMEncoding()
{
if (s_oemEncoding == null)
{
#if UNIX // PowerShell Core on Unix
s_oemEncoding = GetDefaultEncoding();
#elif CORECLR // PowerShell Core on Windows
EncodingRegisterProvider();
uint oemCp = NativeMethods.GetOEMCP();
s_oemEncoding = Encoding.GetEncoding((int)oemCp);
#else // Windows PowerShell
uint oemCp = NativeMethods.GetOEMCP();
s_oemEncoding = Encoding.GetEncoding((int)oemCp);
#endif
}
return s_oemEncoding;
}
private static volatile Encoding s_oemEncoding;
#if CORECLR
private static void EncodingRegisterProvider()
{
if (s_defaultEncoding == null && s_oemEncoding == null)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
}
}
#endif
#endregion Encoding
#region Security
/// <summary>
/// Facade to get the SecurityZone information of a file.
/// </summary>
internal static SecurityZone GetFileSecurityZone(string filePath)
{
Diagnostics.Assert(Path.IsPathRooted(filePath), "Caller makes sure the path is rooted.");
Diagnostics.Assert(Utils.NativeFileExists(filePath), "Caller makes sure the file exists.");
#if CORECLR
string sysRoot = System.Environment.GetEnvironmentVariable("SystemRoot");
string urlmonPath = Path.Combine(sysRoot, @"System32\urlmon.dll");
if (Utils.NativeFileExists(urlmonPath))
{
return MapSecurityZoneWithUrlmon(filePath);
}
return MapSecurityZoneWithoutUrlmon(filePath);
#else
return MapSecurityZoneWithUrlmon(filePath);
#endif
}
#if CORECLR
#region WithoutUrlmon
/// <summary>
/// Map the file to SecurityZone without using urlmon.dll.
/// This is needed on NanoServer because urlmon.dll is not in OneCore.
/// </summary>
/// <remarks>
/// The algorithm is as follows:
///
/// 1. Alternate data stream "Zone.Identifier" is checked first. If this alternate data stream has content, then the content is parsed to determine the SecurityZone.
/// 2. If the alternate data stream "Zone.Identifier" doesn't exist, or its content is not expected, then the file path will be analyzed to determine the SecurityZone.
///
/// For #1, the parsing rules are observed as follows:
/// A. Read content of the data stream line by line. Each line is trimmed.
/// B. Try to match the current line with '^\[ZoneTransfer\]'.
/// - if matching, then do step (#C) starting from the next line
/// - if not matching, then continue to do step (#B) with the next line.
/// C. Try to match the current line with '^ZoneId\s*=\s*(.*)'
/// - if matching, check if the ZoneId is valid. Then return the corresponding SecurityZone if the 'ZoneId' is valid, or 'NoZone' if invalid.
/// - if not matching, then continue to do step (#C) with the next line.
/// D. Reach EOF, then return 'NoZone'.
/// After #1, if the returned SecurityZone is 'NoZone', then proceed with #2. Otherwise, return it as the mapping result.
///
/// For #2, the analysis rules are observed as follows:
/// A. If the path is a UNC path, then
/// - if the host name of the UNC path is IP address, then mapping it to "Internet" zone.
/// - if the host name of the UNC path has dot (.) in it, then mapping it to "internet" zone.
/// - otherwise, mapping it to "intranet" zone.
/// B. If the path is not UNC path, then get the root drive,
/// - if the drive is CDRom, mapping it to "Untrusted" zone
/// - if the drive is Network, mapping it to "Intranet" zone
/// - otherwise, mapping it to "MyComputer" zone.
///
/// The above algorithm has two changes comparing to the behavior of "Zone.CreateFromUrl" I observed:
/// (1) If a file downloaded from internet (ZoneId=3) is not on the local machine, "Zone.CreateFromUrl" won't respect the MOTW.
/// I think it makes more sense for powershell to always check the MOTW first, even for files not on local box.
/// (2) When it's a UNC path and is actually a loopback (\\127.0.0.1\c$\test.txt), "Zone.CreateFromUrl" returns "Internet", but
/// the above algorithm changes it to be "MyComputer" because it's actually the same computer.
/// </remarks>
private static SecurityZone MapSecurityZoneWithoutUrlmon(string filePath)
{
SecurityZone reval = ReadFromZoneIdentifierDataStream(filePath);
if (reval != SecurityZone.NoZone) { return reval; }
// If it reaches here, then we either couldn't get the ZoneId information, or the ZoneId is invalid.
// In this case, we try to determine the SecurityZone by analyzing the file path.
Uri uri = new Uri(filePath);
if (uri.IsUnc)
{
if (uri.IsLoopback)
{
return SecurityZone.MyComputer;
}
if (uri.HostNameType == UriHostNameType.IPv4 ||
uri.HostNameType == UriHostNameType.IPv6)
{
return SecurityZone.Internet;
}
// This is also an observation of Zone.CreateFromUrl/Zone.SecurityZone. If the host name
// has 'dot' in it, the file will be treated as in Internet security zone. Otherwise, it's
// in Intranet security zone.
string hostName = uri.Host;
return hostName.IndexOf('.') == -1 ? SecurityZone.Intranet : SecurityZone.Internet;
}
string root = Path.GetPathRoot(filePath);
DriveInfo drive = new DriveInfo(root);
switch (drive.DriveType)
{
case DriveType.NoRootDirectory:
case DriveType.Unknown:
case DriveType.CDRom:
return SecurityZone.Untrusted;
case DriveType.Network:
return SecurityZone.Intranet;
default:
return SecurityZone.MyComputer;
}
}
/// <summary>
/// Read the 'Zone.Identifier' alternate data stream to determin SecurityZone of the file.
/// </summary>
private static SecurityZone ReadFromZoneIdentifierDataStream(string filePath)
{
try
{
FileStream zoneDataSteam = AlternateDataStreamUtilities.CreateFileStream(
filePath, "Zone.Identifier", FileMode.Open,
FileAccess.Read, FileShare.Read);
// If we successfully get the zone data stream, try to read the ZoneId information
using (StreamReader zoneDataReader = new StreamReader(zoneDataSteam, GetDefaultEncoding()))
{
string line = null;
bool zoneTransferMatched = false;
// After a lot experiments with Zone.CreateFromUrl/Zone.SecurityZone, the way it handles the alternate
// data stream 'Zone.Identifier' is observed as follows:
// 1. Read content of the data stream line by line. Each line is trimmed.
// 2. Try to match the current line with '^\[ZoneTransfer\]'.
// - if matching, then do step #3 starting from the next line
// - if not matching, then continue to do step #2 with the next line.
// 3. Try to match the current line with '^ZoneId\s*=\s*(.*)'
// - if matching, check if the ZoneId is valid. Then return the corresponding SecurityZone if valid, or 'NoZone' if invalid.
// - if not matching, then continue to do step #3 with the next line.
// 4. Reach EOF, then return 'NoZone'.
while ((line = zoneDataReader.ReadLine()) != null)
{
line = line.Trim();
if (!zoneTransferMatched)
{
zoneTransferMatched = Regex.IsMatch(line, @"^\[ZoneTransfer\]", RegexOptions.IgnoreCase);
}
else
{
Match match = Regex.Match(line, @"^ZoneId\s*=\s*(.*)", RegexOptions.IgnoreCase);
if (!match.Success) { continue; }
// Match found. Validate ZoneId value.
string zoneIdRawValue = match.Groups[1].Value;
match = Regex.Match(zoneIdRawValue, @"^[+-]?\d+", RegexOptions.IgnoreCase);
if (!match.Success) { return SecurityZone.NoZone; }
string zoneId = match.Groups[0].Value;
SecurityZone result;
return LanguagePrimitives.TryConvertTo(zoneId, out result) ? result : SecurityZone.NoZone;
}
}
}
}
catch (FileNotFoundException)
{
// FileNotFoundException may be thrown by AlternateDataStreamUtilities.CreateFileStream when the data stream 'Zone.Identifier'
// does not exist, or when the underlying file system doesn't support alternate data stream.
}
return SecurityZone.NoZone;
}
#endregion WithoutUrlmon
#endif
/// <summary>
/// Map the file to SecurityZone using urlmon.dll, depending on 'IInternetSecurityManager::MapUrlToZone'.
/// </summary>
private static SecurityZone MapSecurityZoneWithUrlmon(string filePath)
{
uint zoneId;
object curSecMgr = null;
const UInt32 MUTZ_DONT_USE_CACHE = 0x00001000;
int hr = NativeMethods.CoInternetCreateSecurityManager(null, out curSecMgr, 0);
if (hr != NativeMethods.S_OK)
{
// Returns an error value if it's not S_OK
throw new System.ComponentModel.Win32Exception(hr);
}
try
{
NativeMethods.IInternetSecurityManager ism = (NativeMethods.IInternetSecurityManager)curSecMgr;
hr = ism.MapUrlToZone(filePath, out zoneId, MUTZ_DONT_USE_CACHE);
if (hr == NativeMethods.S_OK)
{
SecurityZone result;
return LanguagePrimitives.TryConvertTo(zoneId, out result) ? result : SecurityZone.NoZone;
}
return SecurityZone.NoZone;
}
finally
{
if (curSecMgr != null)
{
Marshal.ReleaseComObject(curSecMgr);
}
}
}
#endregion Security
#region Culture
/// <summary>
/// Facade for CultureInfo.GetCultureInfo(string).
/// </summary>
internal static CultureInfo GetCultureInfo(string cultureName)
{
#if CORECLR
return new CultureInfo(cultureName);
#else
return CultureInfo.GetCultureInfo(cultureName);
#endif
}
/// <summary>
/// Facade for setting CurrentCulture for the CurrentThread
/// </summary>
internal static void SetCurrentThreadCulture(CultureInfo cultureInfo)
{
#if CORECLR
CultureInfo.CurrentCulture = cultureInfo;
#else
// Setters for 'CultureInfo.CurrentCulture' is introduced in .NET 4.6
Thread.CurrentThread.CurrentCulture = cultureInfo;
#endif
}
/// <summary>
/// Facade for setting CurrentUICulture for the CurrentThread
/// </summary>
internal static void SetCurrentThreadUiCulture(CultureInfo uiCultureInfo)
{
#if CORECLR
CultureInfo.CurrentUICulture = uiCultureInfo;
#else
// Setters for 'CultureInfo.CurrentUICulture' is introduced in .NET 4.6
Thread.CurrentThread.CurrentUICulture = uiCultureInfo;
#endif
}
#endregion Culture
#region Misc
/// <summary>
/// Facade for RemotingServices.IsTransparentProxy(object)
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool IsTransparentProxy(object obj)
{
#if CORECLR // Namespace System.Runtime.Remoting is not in CoreCLR
return false;
#else
return System.Runtime.Remoting.RemotingServices.IsTransparentProxy(obj);
#endif
}
/// <summary>
/// Facade for ManagementDateTimeConverter.ToDmtfDateTime(DateTime)
/// </summary>
internal static string ToDmtfDateTime(DateTime date)
{
#if CORECLR
// This implementation is copied from ManagementDateTimeConverter.ToDmtfDateTime(DateTime date) with a minor adjustment:
// Use TimeZoneInfo.Local instead of TimeZone.CurrentTimeZone. System.TimeZone is not in CoreCLR.
// According to MSDN, CurrentTimeZone property corresponds to the TimeZoneInfo.Local property, and
// it's recommended to use TimeZoneInfo.Local whenever possible.
const int maxsizeUtcDmtf = 999;
string UtcString = String.Empty;
// Fill up the UTC field in the DMTF date with the current zones UTC value
TimeZoneInfo curZone = TimeZoneInfo.Local;
TimeSpan tickOffset = curZone.GetUtcOffset(date);
long OffsetMins = (tickOffset.Ticks / TimeSpan.TicksPerMinute);
IFormatProvider frmInt32 = (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(Int32));
// If the offset is more than that what can be specified in DMTF format, then
// convert the date to UniversalTime
if (Math.Abs(OffsetMins) > maxsizeUtcDmtf)
{
date = date.ToUniversalTime();
UtcString = "+000";
}
else
if ((tickOffset.Ticks >= 0))
{
UtcString = "+" + ((tickOffset.Ticks / TimeSpan.TicksPerMinute)).ToString(frmInt32).PadLeft(3, '0');
}
else
{
string strTemp = OffsetMins.ToString(frmInt32);
UtcString = "-" + strTemp.Substring(1, strTemp.Length - 1).PadLeft(3, '0');
}
string dmtfDateTime = date.Year.ToString(frmInt32).PadLeft(4, '0');
dmtfDateTime = (dmtfDateTime + date.Month.ToString(frmInt32).PadLeft(2, '0'));
dmtfDateTime = (dmtfDateTime + date.Day.ToString(frmInt32).PadLeft(2, '0'));
dmtfDateTime = (dmtfDateTime + date.Hour.ToString(frmInt32).PadLeft(2, '0'));
dmtfDateTime = (dmtfDateTime + date.Minute.ToString(frmInt32).PadLeft(2, '0'));
dmtfDateTime = (dmtfDateTime + date.Second.ToString(frmInt32).PadLeft(2, '0'));
dmtfDateTime = (dmtfDateTime + ".");
// Construct a DateTime with with the precision to Second as same as the passed DateTime and so get
// the ticks difference so that the microseconds can be calculated
DateTime dtTemp = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0);
Int64 microsec = ((date.Ticks - dtTemp.Ticks) * 1000) / TimeSpan.TicksPerMillisecond;
// fill the microseconds field
String strMicrosec = microsec.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(Int64)));
if (strMicrosec.Length > 6)
{
strMicrosec = strMicrosec.Substring(0, 6);
}
dmtfDateTime = dmtfDateTime + strMicrosec.PadLeft(6, '0');
// adding the UTC offset
dmtfDateTime = dmtfDateTime + UtcString;
return dmtfDateTime;
#else
return ManagementDateTimeConverter.ToDmtfDateTime(date);
#endif
}
/// <summary>
/// Manual implementation of the is 64bit processor check
/// </summary>
/// <returns></returns>
internal static bool Is64BitOperatingSystem()
{
#if CORECLR
return (8 == IntPtr.Size); // Pointers are 8 bytes on 64-bit machines
#else
return Environment.Is64BitOperatingSystem;
#endif
}
/// <summary>
/// Facade for FormatterServices.GetUninitializedObject.
///
/// In CORECLR, there are two peculiarities with its implementation that affect our own:
/// 1. Structures cannot be instantiated using GetConstructor, so they must be filtered out.
/// 2. Classes must have a default constructor implemented for GetConstructor to work.
///
/// See RemoteHostEncoder.IsEncodingAllowedForClassOrStruct for a list of the required types.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
internal static object GetUninitializedObject(Type type)
{
#if CORECLR
switch (type.Name)
{
case "KeyInfo"://typeof(KeyInfo).Name:
return new KeyInfo(0, ' ', ControlKeyStates.RightAltPressed, false);
case "Coordinates"://typeof(Coordinates).Name:
return new Coordinates(0, 0);
case "Size"://typeof(Size).Name:
return new Size(0, 0);
case "BufferCell"://typeof(BufferCell).Name:
return new BufferCell(' ', ConsoleColor.Black, ConsoleColor.Black, BufferCellType.Complete);
case "Rectangle"://typeof(Rectangle).Name:
return new Rectangle(0, 0, 0, 0);
default:
ConstructorInfo constructorInfoObj = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
if (constructorInfoObj != null)
{
return constructorInfoObj.Invoke(new object[] { });
}
return new object();
}
#else
return FormatterServices.GetUninitializedObject(type);
#endif
}
/// <summary>
/// Facade for setting WaitHandle.SafeWaitHandle.
/// </summary>
/// <param name="waitHandle"></param>
/// <param name="value"></param>
internal static void SetSafeWaitHandle(WaitHandle waitHandle, SafeWaitHandle value)
{
#if CORECLR
waitHandle.SetSafeWaitHandle(value);
#else
waitHandle.SafeWaitHandle = value;
#endif
}
/// <summary>
/// Facade for ProfileOptimization.SetProfileRoot
/// </summary>
/// <param name="directoryPath">The full path to the folder where profile files are stored for the current application domain.</param>
internal static void SetProfileOptimizationRoot(string directoryPath)
{
#if CORECLR
PSAssemblyLoadContext.SetProfileOptimizationRootImpl(directoryPath);
#else
System.Runtime.ProfileOptimization.SetProfileRoot(directoryPath);
#endif
}
/// <summary>
/// Facade for ProfileOptimization.StartProfile
/// </summary>
/// <param name="profile">The file name of the profile to use.</param>
internal static void StartProfileOptimization(string profile)
{
#if CORECLR
PSAssemblyLoadContext.StartProfileOptimizationImpl(profile);
#else
System.Runtime.ProfileOptimization.StartProfile(profile);
#endif
}
#endregion Misc
/// <summary>
/// Native methods that are used by facade methods
/// </summary>
private static class NativeMethods
{
/// <summary>
/// Pinvoke for GetOEMCP to get the OEM code page.
/// </summary>
[DllImport(PinvokeDllNames.GetOEMCPDllName, SetLastError = false, CharSet = CharSet.Unicode)]
internal static extern uint GetOEMCP();
/// <summary>
/// Pinvoke for GetACP to get the Windows operating system code page.
/// </summary>
[DllImport(PinvokeDllNames.GetACPDllName, SetLastError = false, CharSet = CharSet.Unicode)]
internal static extern uint GetACP();
public const int S_OK = 0x00000000;
/// <summary>
/// Pinvoke to create an IInternetSecurityManager interface..
/// </summary>
[DllImport("urlmon.dll", ExactSpelling = true)]
internal static extern int CoInternetCreateSecurityManager([MarshalAs(UnmanagedType.Interface)] object pIServiceProvider,
[MarshalAs(UnmanagedType.Interface)] out object ppISecurityManager,
int dwReserved);
/// <summary>
/// IInternetSecurityManager interface
/// </summary>
[ComImport, ComVisible(false), Guid("79EAC9EE-BAF9-11CE-8C82-00AA004BA90B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IInternetSecurityManager
{
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int SetSecuritySite([In] IntPtr pSite);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int GetSecuritySite([Out] IntPtr pSite);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int MapUrlToZone([In, MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, out uint pdwZone, uint dwFlags);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int GetSecurityId([MarshalAs(UnmanagedType.LPWStr)] string pwszUrl,
[MarshalAs(UnmanagedType.LPArray)] byte[] pbSecurityId,
ref uint pcbSecurityId, uint dwReserved);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int ProcessUrlAction([In, MarshalAs(UnmanagedType.LPWStr)] string pwszUrl,
uint dwAction, out byte pPolicy, uint cbPolicy,
byte pContext, uint cbContext, uint dwFlags,
uint dwReserved);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int QueryCustomPolicy([In, MarshalAs(UnmanagedType.LPWStr)] string pwszUrl,
ref Guid guidKey, ref byte ppPolicy, ref uint pcbPolicy,
ref byte pContext, uint cbContext, uint dwReserved);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int SetZoneMapping(uint dwZone, [In, MarshalAs(UnmanagedType.LPWStr)] string lpszPattern, uint dwFlags);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int GetZoneMappings(uint dwZone, out IEnumString ppenumString, uint dwFlags);
}
}
}
}