1 //------------------------------------------------------------------------------
3 // System.Environment.cs
5 // Copyright (C) 2001 Moonlight Enterprises, All Rights Reserved
7 // Author: Jim Richardson, develop@wtfo-guru.com
8 // Dan Lewis (dihlewis@yahoo.co.uk)
9 // Created: Saturday, August 11, 2001
11 //------------------------------------------------------------------------------
13 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Collections;
37 using System.Runtime.CompilerServices;
38 using System.Security;
39 using System.Security.Permissions;
45 public static class Environment {
47 public sealed class Environment {
49 private Environment ()
54 * This is the version number of the corlib-runtime interface. When
55 * making changes to this interface (by changing the layout
56 * of classes the runtime knows about, changing icall semantics etc),
57 * increment this variable. Also increment the
58 * pair of this variable in the runtime in metadata/appdomain.c.
59 * Changes which are already detected at runtime, like the addition
60 * of icalls, do not require an increment.
62 private const int mono_corlib_version = 32;
65 public enum SpecialFolder
66 { // TODO: Determine if these windoze style folder identifiers
67 // have unix/linux counterparts
83 DesktopDirectory = 0x10,
85 ApplicationData = 0x1a,
86 LocalApplicationData = 0x1c,
90 CommonApplicationData = 0x23,
94 CommonProgramFiles = 0x2b,
98 /// Gets the command line for this process
100 public static string CommandLine {
101 // note: security demand inherited from calling GetCommandLineArgs
103 // FIXME: we may need to quote, but any sane person
104 // should use GetCommandLineArgs () instead.
105 return String.Join (" ", GetCommandLineArgs ());
110 /// Gets or sets the current directory. Actually this is supposed to get
111 /// and/or set the process start directory acording to the documentation
112 /// but actually test revealed at beta2 it is just Getting/Setting the CurrentDirectory
114 public static string CurrentDirectory
117 return Directory.GetCurrentDirectory ();
120 Directory.SetCurrentDirectory (value);
125 /// Gets or sets the exit code of this process
127 public extern static int ExitCode
129 [MethodImplAttribute (MethodImplOptions.InternalCall)]
131 [MethodImplAttribute (MethodImplOptions.InternalCall)]
138 public extern bool HasShutdownStarted
140 [MethodImplAttribute (MethodImplOptions.InternalCall)]
146 /// Gets the name of the local computer
148 public extern static string MachineName {
149 [MethodImplAttribute (MethodImplOptions.InternalCall)]
150 [EnvironmentPermission (SecurityAction.Demand, Read="COMPUTERNAME")]
151 [SecurityPermission (SecurityAction.Demand, UnmanagedCode=true)]
156 /// Gets the standard new line value
158 public extern static string NewLine {
159 [MethodImplAttribute (MethodImplOptions.InternalCall)]
164 // Support methods and fields for OSVersion property
166 static OperatingSystem os;
168 internal static extern PlatformID Platform {
169 [MethodImplAttribute (MethodImplOptions.InternalCall)]
173 [MethodImplAttribute (MethodImplOptions.InternalCall)]
174 internal static extern string GetOSVersionString ();
177 /// Gets the current OS version information
179 public static OperatingSystem OSVersion {
182 Version v = Version.CreateFromString (GetOSVersionString ());
183 os = new OperatingSystem (Platform, v);
192 public static string StackTrace {
193 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
195 System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace (1);
196 return trace.ToString ();
201 /// Get a fully qualified path to the system directory
203 public static string SystemDirectory {
205 return GetFolderPath (SpecialFolder.System);
210 /// Get the number of milliseconds that have elapsed since the system was booted
212 public extern static int TickCount {
213 [MethodImplAttribute (MethodImplOptions.InternalCall)]
218 /// Get UserDomainName
220 public static string UserDomainName {
221 // FIXME: this variable doesn't exist (at least not on WinXP) - reported to MS as FDBK20562
222 [EnvironmentPermission (SecurityAction.Demand, Read="USERDOMAINNAME")]
229 /// Gets a flag indicating whether the process is in interactive mode
232 public static bool UserInteractive {
239 /// Get the user name of current process is running under
241 public extern static string UserName {
242 [MethodImplAttribute (MethodImplOptions.InternalCall)]
243 [EnvironmentPermission (SecurityAction.Demand, Read="USERNAME;USER")]
248 /// Get the version of the common language runtime
250 public static Version Version {
253 // FIXME: this is the version number for MS.NET 2.0 beta1.
254 // It must be changed when the final version is released.
255 return new Version (2, 0, 40607, 16);
257 return new Version (1, 1, 4322, 573);
259 return new Version (1, 0, 3705, 288);
265 /// Get the amount of physical memory mapped to process
268 public static long WorkingSet {
269 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
273 [MethodImplAttribute (MethodImplOptions.InternalCall)]
274 [SecurityPermission (SecurityAction.Demand, UnmanagedCode=true)]
275 public extern static void Exit (int exitCode);
278 /// Substitute environment variables in the argument "name"
280 public static string ExpandEnvironmentVariables (string name)
283 throw new ArgumentNullException ("name");
285 int off1 = name.IndexOf ('%');
289 int len = name.Length;
291 if (off1 == len - 1 || (off2 = name.IndexOf ('%', off1 + 1)) == -1)
294 PlatformID platform = Platform;
295 StringBuilder result = new StringBuilder ();
296 result.Append (name, 0, off1);
297 Hashtable tbl = null;
299 string var = name.Substring (off1 + 1, off2 - off1 - 1);
300 string value = GetEnvironmentVariable (var);
301 if (value == null && (int) platform != 128) {
302 // On windows, env. vars. are case insensitive
304 tbl = GetEnvironmentVariablesNoCase ();
306 value = tbl [var] as string;
309 // If value not found, add %FOO to stream,
310 // and use the closing % for the next iteration.
311 // If value found, expand it in place of %FOO%
317 result.Append (value);
320 off1 = name.IndexOf ('%', off2 + 1);
321 // If no % found for off1, don't look for one for off2
322 off2 = (off1 == -1 || off2 > len-1)? -1 :name.IndexOf ('%', off1 + 1);
323 // textLen is the length of text between the closing % of current iteration
324 // and the starting % of the next iteration if any. This text is added to output
326 // If no new % found, use all the remaining text
327 if (off1 == -1 || off2 == -1)
328 textLen = len - oldOff2 - 1;
329 // If value found in current iteration, use text after current closing % and next %
330 else if(value != null)
331 textLen = off1 - oldOff2 - 1;
332 // If value not found in current iteration, but a % was found for next iteration,
333 // use text from current closing % to the next %.
335 textLen = off1 - oldOff2;
336 if(off1 >= oldOff2 || off1 == -1)
337 result.Append (name.Substring (oldOff2+1, textLen));
338 } while (off2 > -1 && off2 < len);
340 return result.ToString ();
345 /// Return an array of the command line arguments of the current process
347 [MethodImplAttribute (MethodImplOptions.InternalCall)]
348 [EnvironmentPermissionAttribute (SecurityAction.Demand, Read = "PATH")]
349 public extern static string[] GetCommandLineArgs ();
351 [MethodImplAttribute (MethodImplOptions.InternalCall)]
352 internal extern static string internalGetEnvironmentVariable (string name);
355 /// Return a string containing the value of the environment
356 /// variable identifed by parameter "variable"
358 public static string GetEnvironmentVariable (string name)
360 if (SecurityManager.SecurityEnabled) {
361 new EnvironmentPermission (EnvironmentPermissionAccess.Read, name).Demand ();
363 return internalGetEnvironmentVariable (name);
366 static Hashtable GetEnvironmentVariablesNoCase ()
368 Hashtable vars = new Hashtable (CaseInsensitiveHashCodeProvider.Default,
369 CaseInsensitiveComparer.Default);
371 foreach (string name in GetEnvironmentVariableNames ()) {
372 vars [name] = internalGetEnvironmentVariable (name);
379 /// Return a set of all environment variables and their values
382 public static IDictionary GetEnvironmentVariables ()
384 StringBuilder sb = null;
385 if (SecurityManager.SecurityEnabled) {
386 // we must have access to each variable to get the lot
387 sb = new StringBuilder ();
388 // but (performance-wise) we do not want a stack-walk
389 // for each of them so we concatenate them
392 Hashtable vars = new Hashtable ();
393 foreach (string name in GetEnvironmentVariableNames ()) {
394 vars [name] = internalGetEnvironmentVariable (name);
402 new EnvironmentPermission (EnvironmentPermissionAccess.Read, sb.ToString ()).Demand ();
408 [MethodImplAttribute (MethodImplOptions.InternalCall)]
409 private extern static string GetWindowsFolderPath (int folder);
412 /// Returns the fully qualified path of the
413 /// folder specified by the "folder" parameter
415 public static string GetFolderPath (SpecialFolder folder)
419 if ((int) Platform != 128) {
420 dir = GetWindowsFolderPath ((int) folder);
422 dir = InternalGetFolderPath (folder);
425 if ((dir != null) && (dir.Length > 0) && SecurityManager.SecurityEnabled) {
426 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dir).Demand ();
431 // the security runtime (and maybe other parts of corlib) needs the
432 // information to initialize themselves before permissions can be checked
433 internal static string InternalGetFolderPath (SpecialFolder folder)
435 string home = internalGetHome ();
437 // http://freedesktop.org/Standards/basedir-spec/basedir-spec-0.6.html
439 // note: skip security check for environment variables
440 string data = internalGetEnvironmentVariable ("XDG_DATA_HOME");
441 if ((data == null) || (data == String.Empty)) {
442 data = Path.Combine (home, ".local");
443 data = Path.Combine (data, "share");
446 // note: skip security check for environment variables
447 string config = internalGetEnvironmentVariable ("XDG_CONFIG_HOME");
448 if ((config == null) || (config == String.Empty)) {
449 config = Path.Combine (home, ".config");
454 // MyComputer is a virtual directory
455 case SpecialFolder.MyComputer:
459 case SpecialFolder.Personal:
461 // use FDO's CONFIG_HOME. This data will be synced across a network like the windows counterpart.
462 case SpecialFolder.ApplicationData:
464 //use FDO's DATA_HOME. This is *NOT* synced
465 case SpecialFolder.LocalApplicationData:
468 case SpecialFolder.Desktop:
470 case SpecialFolder.DesktopDirectory:
471 return Path.Combine (home, "Desktop");
473 // these simply dont exist on Linux
474 // The spec says if a folder doesnt exist, we
476 case SpecialFolder.Favorites:
477 case SpecialFolder.Programs:
478 case SpecialFolder.SendTo:
479 case SpecialFolder.StartMenu:
480 case SpecialFolder.Startup:
481 case SpecialFolder.MyMusic:
482 case SpecialFolder.MyPictures:
483 case SpecialFolder.Templates:
484 case SpecialFolder.Cookies:
485 case SpecialFolder.History:
486 case SpecialFolder.InternetCache:
487 case SpecialFolder.Recent:
488 case SpecialFolder.CommonProgramFiles:
489 case SpecialFolder.ProgramFiles:
490 case SpecialFolder.System:
492 // This is where data common to all users goes
493 case SpecialFolder.CommonApplicationData:
496 throw new ArgumentException ("Invalid SpecialFolder");
500 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
501 public static string[] GetLogicalDrives ()
503 return GetLogicalDrivesInternal ();
506 // FIXME: Anyone using this anywhere ?
507 static internal string GetResourceString (string s) { return ""; }
511 [MonoTODO ("Machine and User targets aren't supported")]
512 public static string GetEnvironmentVariable (string variable, EnvironmentVariableTarget target)
515 case EnvironmentVariableTarget.Process:
516 return GetEnvironmentVariable (variable);
517 case EnvironmentVariableTarget.Machine:
518 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
519 // under Windows this reads the LOCAL_MACHINE registry key for env vars
520 throw new NotImplementedException ();
521 case EnvironmentVariableTarget.User:
522 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
523 // under Windows this reads the CURRENT_USER registry key for env vars
524 throw new NotImplementedException ();
526 throw new ArgumentException ("target");
530 [MonoTODO ("Machine and User targets aren't supported")]
531 public static IDictionary GetEnvironmentVariables (EnvironmentVariableTarget target)
534 case EnvironmentVariableTarget.Process:
535 return GetEnvironmentVariables ();
536 case EnvironmentVariableTarget.Machine:
537 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
538 // under Windows this reads the LOCAL_MACHINE registry key for env vars
539 throw new NotImplementedException ();
540 case EnvironmentVariableTarget.User:
541 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
542 // under Windows this reads the CURRENT_USER registry key for env vars
543 throw new NotImplementedException ();
545 throw new ArgumentException ("target");
550 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
551 public static void SetEnvironmentVariable (string variable, string value)
553 InternalSetEnvironmentVariable (variable, value);
557 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
558 public static void SetEnvironmentVariable (string variable, string value, EnvironmentVariableTarget target)
561 case EnvironmentVariableTarget.Process:
562 InternalSetEnvironmentVariable (variable, value);
564 case EnvironmentVariableTarget.Machine:
565 // under Windows this reads the LOCAL_MACHINE registry key for env vars
566 throw new NotImplementedException ();
567 case EnvironmentVariableTarget.User:
568 // under Windows this reads the CURRENT_USER registry key for env vars
569 throw new NotImplementedException ();
571 throw new ArgumentException ("target");
575 // FIXME: to be changed as an icall when implemented
576 internal static void InternalSetEnvironmentVariable (string variable, string value)
578 throw new NotImplementedException ();
582 public static int ProcessorCount {
583 [EnvironmentPermission (SecurityAction.Demand, Read="NUMBER_OF_PROCESSORS")]
585 // note: Changes to the NUMBER_OF_PROCESSORS environment variable
586 // under Windows doesn't affect the (good) value returned.
587 throw new NotImplementedException ();
591 [MonoTODO ("not much documented")]
592 // FIXME: doesn't seems to have any protection ?!? reported as FDBK20543
593 public static void FailFast (string message)
595 throw new NotImplementedException ();
601 private static string GacPath {
603 if ((int) Platform != 128) {
604 /* On windows, we don't know the path where mscorlib.dll will be installed */
605 string corlibDir = new DirectoryInfo (Path.GetDirectoryName (typeof (int).Assembly.Location)).Parent.Parent.FullName;
606 return Path.Combine (Path.Combine (corlibDir, "mono"), "gac");
609 return Path.Combine (Path.Combine (internalGetGacPath (), "mono"), "gac");
613 [MethodImplAttribute (MethodImplOptions.InternalCall)]
614 private extern static string [] GetLogicalDrivesInternal ();
616 [MethodImplAttribute (MethodImplOptions.InternalCall)]
617 private extern static string [] GetEnvironmentVariableNames ();
619 [MethodImplAttribute (MethodImplOptions.InternalCall)]
620 internal extern static string GetMachineConfigPath ();
622 [MethodImplAttribute (MethodImplOptions.InternalCall)]
623 internal extern static string internalGetGacPath ();
625 [MethodImplAttribute (MethodImplOptions.InternalCall)]
626 internal extern static string internalGetHome ();