forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnv.cs
More file actions
364 lines (307 loc) · 13.5 KB
/
Env.cs
File metadata and controls
364 lines (307 loc) · 13.5 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
//Copyright (c) ServiceStack, Inc. All Rights Reserved.
//License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt
using System;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace ServiceStack.Text;
public static class Env
{
static Env()
{
if (PclExport.Instance == null)
throw new ArgumentException("PclExport.Instance needs to be initialized");
#if NETCORE
IsNetStandard = true;
try
{
IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
IsOSX = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
IsNetCore3 = RuntimeInformation.FrameworkDescription.StartsWith(".NET Core 3");
var fxDesc = RuntimeInformation.FrameworkDescription;
IsMono = fxDesc.Contains("Mono");
IsNetCore = fxDesc.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase);
}
catch (Exception) {} //throws PlatformNotSupportedException in AWS lambda
IsUnix = IsOSX || IsLinux;
HasMultiplePlatformTargets = true;
IsUWP = IsRunningAsUwp();
#elif NETFX
IsNetFramework = true;
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32NT:
case PlatformID.Win32S:
case PlatformID.Win32Windows:
case PlatformID.WinCE:
IsWindows = true;
break;
}
var platform = (int)Environment.OSVersion.Platform;
IsUnix = platform is 4 or 6 or 128;
if (File.Exists(@"/System/Library/CoreServices/SystemVersion.plist"))
IsOSX = true;
var osType = File.Exists(@"/proc/sys/kernel/ostype")
? File.ReadAllText(@"/proc/sys/kernel/ostype")
: null;
IsLinux = osType?.IndexOf("Linux", StringComparison.OrdinalIgnoreCase) >= 0;
try
{
IsMono = AssemblyUtils.FindType("Mono.Runtime") != null;
}
catch (Exception) {}
SupportsDynamic = true;
#endif
#if NETCORE
IsNetStandard = false;
IsNetCore = true;
SupportsDynamic = true;
IsNetCore21 = true;
#endif
#if NET8_0_OR_GREATER
IsNet8 = true;
#elif NET6_0_OR_GREATER
IsNet6 = true;
#endif
#if NETSTANDARD2_0
IsNetStandard20 = true;
#endif
if (!IsUWP)
{
try
{
IsAndroid = AssemblyUtils.FindType("Android.Manifest") != null;
if (IsOSX && IsMono)
{
var runtimeDir = RuntimeEnvironment.GetRuntimeDirectory();
//iOS detection no longer trustworthy so assuming iOS based on some current heuristics. TODO: improve iOS detection
IsIOS = runtimeDir.StartsWith("/private/var") ||
runtimeDir.Contains("/CoreSimulator/Devices/");
}
}
catch (Exception) {}
}
#if NET6_0_OR_GREATER
if (OperatingSystem.IsIOS()) IsIOS = true;
#endif
SupportsExpressions = true;
SupportsEmit = !(IsUWP || IsIOS);
if (!SupportsEmit)
{
ReflectionOptimizer.Instance = ExpressionReflectionOptimizer.Provider;
}
VersionString = ServiceStackVersion.ToString(CultureInfo.InvariantCulture);
__releaseDate = new DateTime(2001,01,01);
UpdateServerUserAgent();
}
internal static bool IsAot()
{
#if NET6_0_OR_GREATER
return OperatingSystem.IsIOS() || !RuntimeFeature.IsDynamicCodeSupported;
#endif
return false;
}
internal static void UpdateServerUserAgent()
{
ServerUserAgent = "ServiceStack/"
+ VersionString + " "
+ PclExport.Instance.PlatformName
+ (IsLinux ? "/Linux" : IsOSX ? "/macOS" : IsUnix ? "/Unix" : IsWindows ? "/Windows" : "/UnknownOS")
+ (IsIOS ? "/iOS" : IsAndroid ? "/Android" : IsUWP ? "/UWP" : "")
+ (IsNet8 ? "/net8" : IsNet6 ? "/net6" : IsNetStandard20 ? "/std2.0" : IsNetFramework ? "/netfx" : "") + (IsMono ? "/Mono" : "")
+ $"/{LicenseUtils.Info}";
}
public static string VersionString { get; set; }
public static decimal ServiceStackVersion = 8.81m;
public static bool IsLinux { get; set; }
public static bool IsOSX { get; set; }
public static bool IsUnix { get; set; }
public static bool IsWindows { get; set; }
public static bool IsMono { get; set; }
public static bool IsIOS { get; set; }
public static bool IsAndroid { get; set; }
public static bool IsNetNative { get; set; }
public static bool IsUWP { get; private set; }
public static bool IsNetStandard { get; set; }
public static bool IsNetCore21 { get; set; }
public static bool IsNet6 { get; set; }
public static bool IsNet8 { get; set; }
public static bool IsNetStandard20 { get; set; }
public static bool IsNetFramework { get; set; }
public static bool IsNetCore { get; set; }
public static bool IsNetCore3 { get; set; }
public static bool SupportsExpressions { get; private set; }
public static bool SupportsEmit { get; private set; }
public static bool SupportsDynamic { get; private set; }
private static bool strictMode;
public static bool StrictMode
{
get => strictMode;
set => Config.Instance.ThrowOnError = strictMode = value;
}
public static string ServerUserAgent { get; set; }
public static bool HasMultiplePlatformTargets { get; set; }
private static readonly DateTime __releaseDate;
public static DateTime GetReleaseDate()
{
return __releaseDate;
}
private static string referenceAssemblyPath;
public static string ReferenceAssemblyPath
{
get
{
if (!IsMono && referenceAssemblyPath == null)
{
var programFilesPath = PclExport.Instance.GetEnvironmentVariable("ProgramFiles(x86)") ?? @"C:\Program Files (x86)";
var netFxReferenceBasePath = programFilesPath + @"\Reference Assemblies\Microsoft\Framework\.NETFramework\";
if ((netFxReferenceBasePath + @"v4.5.2\").DirectoryExists())
referenceAssemblyPath = netFxReferenceBasePath + @"v4.5.2\";
else if ((netFxReferenceBasePath + @"v4.5.1\").DirectoryExists())
referenceAssemblyPath = netFxReferenceBasePath + @"v4.5.1\";
else if ((netFxReferenceBasePath + @"v4.5\").DirectoryExists())
referenceAssemblyPath = netFxReferenceBasePath + @"v4.5\";
else if ((netFxReferenceBasePath + @"v4.0\").DirectoryExists())
referenceAssemblyPath = netFxReferenceBasePath + @"v4.0\";
else
{
var v4Dirs = PclExport.Instance.GetDirectoryNames(netFxReferenceBasePath, "v4*");
if (v4Dirs.Length == 0)
{
var winPath = PclExport.Instance.GetEnvironmentVariable("SYSTEMROOT") ?? @"C:\Windows";
var gacPath = winPath + @"\Microsoft.NET\Framework\";
v4Dirs = PclExport.Instance.GetDirectoryNames(gacPath, "v4*");
}
if (v4Dirs.Length > 0)
{
referenceAssemblyPath = v4Dirs[v4Dirs.Length - 1] + @"\"; //latest v4
}
else
{
throw new FileNotFoundException(
"Could not infer .NET Reference Assemblies path, e.g '{0}'.\n".Fmt(netFxReferenceBasePath + @"v4.0\") +
"Provide path manually 'Env.ReferenceAssemblyPath'.");
}
}
}
return referenceAssemblyPath;
}
set => referenceAssemblyPath = value;
}
#if NETCORE
private static bool IsRunningAsUwp()
{
try
{
IsNetNative = RuntimeInformation.FrameworkDescription.StartsWith(".NET Native", StringComparison.OrdinalIgnoreCase);
return IsInAppContainer || IsNetNative;
}
catch (Exception) {}
return false;
}
private static bool IsWindows7OrLower
{
get
{
int versionMajor = Environment.OSVersion.Version.Major;
int versionMinor = Environment.OSVersion.Version.Minor;
double version = versionMajor + (double)versionMinor / 10;
return version <= 6.1;
}
}
// From: https://github.com/dotnet/corefx/blob/master/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.Windows.cs
private static int s_isInAppContainer = -1;
private static bool IsInAppContainer
{
// This actually checks whether code is running in a modern app.
// Currently this is the only situation where we run in app container.
// If we want to distinguish the two cases in future,
// EnvironmentHelpers.IsAppContainerProcess in desktop code shows how to check for the AC token.
get
{
if (s_isInAppContainer != -1)
return s_isInAppContainer == 1;
if (!IsWindows || IsWindows7OrLower)
{
s_isInAppContainer = 0;
return false;
}
byte[] buffer = TypeConstants.EmptyByteArray;
uint bufferSize = 0;
try
{
int result = GetCurrentApplicationUserModelId(ref bufferSize, buffer);
switch (result)
{
case 15703: // APPMODEL_ERROR_NO_APPLICATION
s_isInAppContainer = 0;
break;
case 0: // ERROR_SUCCESS
case 122: // ERROR_INSUFFICIENT_BUFFER
// Success is actually insufficient buffer as we're really only looking for
// not NO_APPLICATION and we're not actually giving a buffer here. The
// API will always return NO_APPLICATION if we're not running under a
// WinRT process, no matter what size the buffer is.
s_isInAppContainer = 1;
break;
default:
throw new InvalidOperationException($"Failed to get AppId, result was {result}.");
}
}
catch (Exception e)
{
// We could catch this here, being friendly with older portable surface area should we
// desire to use this method elsewhere.
if (e.GetType().FullName.Equals("System.EntryPointNotFoundException", StringComparison.Ordinal))
{
// API doesn't exist, likely pre Win8
s_isInAppContainer = 0;
}
else
{
throw;
}
}
return s_isInAppContainer == 1;
}
}
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern int GetCurrentApplicationUserModelId(ref uint applicationUserModelIdLength, byte[] applicationUserModelId);
#endif
public const bool ContinueOnCapturedContext = false;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ConfiguredTaskAwaitable ConfigAwait(this Task task) =>
task.ConfigureAwait(ContinueOnCapturedContext);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ConfiguredTaskAwaitable<T> ConfigAwait<T>(this Task<T> task) =>
task.ConfigureAwait(ContinueOnCapturedContext);
/// <summary>
/// Only .ConfigAwait(false) in .NET Core as loses HttpContext.Current in NETFX/ASP.NET
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#if NETCORE
public static ConfiguredTaskAwaitable ConfigAwaitNetCore(this Task task) => task.ConfigureAwait(false);
#else
public static Task ConfigAwaitNetCore(this Task task) => task;
#endif
/// <summary>
/// Only .ConfigAwait(false) in .NET Core as loses HttpContext.Current in NETFX/ASP.NET
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#if NETCORE
public static ConfiguredTaskAwaitable<T> ConfigAwaitNetCore<T>(this Task<T> task) => task.ConfigureAwait(false);
#else
public static Task<T> ConfigAwaitNetCore<T>(this Task<T> task) => task;
#endif
#if NETCORE
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ConfiguredValueTaskAwaitable ConfigAwait(this ValueTask task) =>
task.ConfigureAwait(ContinueOnCapturedContext);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ConfiguredValueTaskAwaitable<T> ConfigAwait<T>(this ValueTask<T> task) =>
task.ConfigureAwait(ContinueOnCapturedContext);
#endif
}