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;
41 using System.Runtime.InteropServices;
46 public static class Environment {
49 * This is the version number of the corlib-runtime interface. When
50 * making changes to this interface (by changing the layout
51 * of classes the runtime knows about, changing icall signature or
52 * semantics etc), increment this variable. Also increment the
53 * pair of this variable in the runtime in metadata/appdomain.c.
54 * Changes which are already detected at runtime, like the addition
55 * of icalls, do not require an increment.
57 #pragma warning disable 169
58 private const int mono_corlib_version = 93;
59 #pragma warning restore 169
62 public enum SpecialFolder
75 DesktopDirectory = 0x10,
77 ApplicationData = 0x1a,
78 LocalApplicationData = 0x1c,
82 CommonApplicationData = 0x23,
86 CommonProgramFiles = 0x2b,
87 #if NET_4_0 || MOONLIGHT
91 NetworkShortcuts = 0x13,
93 CommonStartMenu = 0x16,
94 CommonPrograms = 0x17,
96 CommonDesktopDirectory = 0x19,
97 PrinterShortcuts = 0x1b,
101 ProgramFilesX86 = 0x2a,
102 CommonProgramFilesX86 = 0x2c,
103 CommonTemplates = 0x2d,
104 CommonDocuments = 0x2e,
105 CommonAdminTools = 0x2f,
108 CommonPictures = 0x36,
111 LocalizedResources = 0x39,
112 CommonOemLinks = 0x3a,
120 enum SpecialFolderOption {
122 DoNotVerify = 0x4000,
127 /// Gets the command line for this process
129 public static string CommandLine {
130 // note: security demand inherited from calling GetCommandLineArgs
132 StringBuilder sb = new StringBuilder ();
133 foreach (string str in GetCommandLineArgs ()) {
137 for (int i = 0; i < s.Length; i++) {
138 if (quote.Length == 0 && Char.IsWhiteSpace (s [i])) {
140 } else if (s [i] == '"') {
144 if (escape && quote.Length != 0) {
145 s = s.Replace ("\"", "\\\"");
147 sb.AppendFormat ("{0}{1}{0} ", quote, s);
151 return sb.ToString ();
156 /// Gets or sets the current directory. Actually this is supposed to get
157 /// and/or set the process start directory acording to the documentation
158 /// but actually test revealed at beta2 it is just Getting/Setting the CurrentDirectory
160 public static string CurrentDirectory
163 return Directory.GetCurrentDirectory ();
166 Directory.SetCurrentDirectory (value);
171 /// Gets or sets the exit code of this process
173 public extern static int ExitCode
175 [MethodImplAttribute (MethodImplOptions.InternalCall)]
177 [MethodImplAttribute (MethodImplOptions.InternalCall)]
181 static public extern bool HasShutdownStarted
183 [MethodImplAttribute (MethodImplOptions.InternalCall)]
189 /// Gets the name of the local computer
191 public extern static string MachineName {
192 [MethodImplAttribute (MethodImplOptions.InternalCall)]
193 [EnvironmentPermission (SecurityAction.Demand, Read="COMPUTERNAME")]
194 [SecurityPermission (SecurityAction.Demand, UnmanagedCode=true)]
199 /// Gets the standard new line value
201 public extern static string NewLine {
202 [MethodImplAttribute (MethodImplOptions.InternalCall)]
207 // Support methods and fields for OSVersion property
209 static OperatingSystem os;
211 internal static extern PlatformID Platform {
212 [MethodImplAttribute (MethodImplOptions.InternalCall)]
216 [MethodImplAttribute (MethodImplOptions.InternalCall)]
217 internal static extern string GetOSVersionString ();
220 /// Gets the current OS version information
222 public static OperatingSystem OSVersion {
225 Version v = Version.CreateFromString (GetOSVersionString ());
226 PlatformID p = Platform;
227 os = new OperatingSystem (p, v);
236 public static string StackTrace {
237 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
239 System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace (0, true);
240 return trace.ToString ();
245 /// Get a fully qualified path to the system directory
247 public static string SystemDirectory {
249 return GetFolderPath (SpecialFolder.System);
254 /// Get the number of milliseconds that have elapsed since the system was booted
256 public extern static int TickCount {
257 [MethodImplAttribute (MethodImplOptions.InternalCall)]
262 /// Get UserDomainName
264 public static string UserDomainName {
265 // FIXME: this variable doesn't exist (at least not on WinXP) - reported to MS as FDBK20562
266 [EnvironmentPermission (SecurityAction.Demand, Read="USERDOMAINNAME")]
273 /// Gets a flag indicating whether the process is in interactive mode
275 [MonoTODO ("Currently always returns false, regardless of interactive state")]
276 public static bool UserInteractive {
283 /// Get the user name of current process is running under
285 public extern static string UserName {
286 [MethodImplAttribute (MethodImplOptions.InternalCall)]
287 [EnvironmentPermission (SecurityAction.Demand, Read="USERNAME;USER")]
292 /// Get the version of the common language runtime
294 public static Version Version {
296 return new Version (Consts.FxFileVersion);
301 /// Get the amount of physical memory mapped to process
303 [MonoTODO ("Currently always returns zero")]
304 public static long WorkingSet {
305 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
309 [MethodImplAttribute (MethodImplOptions.InternalCall)]
310 [SecurityPermission (SecurityAction.Demand, UnmanagedCode=true)]
311 public extern static void Exit (int exitCode);
314 /// Substitute environment variables in the argument "name"
316 public static string ExpandEnvironmentVariables (string name)
319 throw new ArgumentNullException ("name");
321 int off1 = name.IndexOf ('%');
325 int len = name.Length;
327 if (off1 == len - 1 || (off2 = name.IndexOf ('%', off1 + 1)) == -1)
330 StringBuilder result = new StringBuilder ();
331 result.Append (name, 0, off1);
332 Hashtable tbl = null;
334 string var = name.Substring (off1 + 1, off2 - off1 - 1);
335 string value = GetEnvironmentVariable (var);
336 if (value == null && Environment.IsRunningOnWindows) {
337 // On windows, env. vars. are case insensitive
339 tbl = GetEnvironmentVariablesNoCase ();
341 value = tbl [var] as string;
344 // If value not found, add %FOO to stream,
345 // and use the closing % for the next iteration.
346 // If value found, expand it in place of %FOO%
352 result.Append (value);
355 off1 = name.IndexOf ('%', off2 + 1);
356 // If no % found for off1, don't look for one for off2
357 off2 = (off1 == -1 || off2 > len-1)? -1 :name.IndexOf ('%', off1 + 1);
358 // textLen is the length of text between the closing % of current iteration
359 // and the starting % of the next iteration if any. This text is added to output
361 // If no new % found, use all the remaining text
362 if (off1 == -1 || off2 == -1)
363 textLen = len - oldOff2 - 1;
364 // If value found in current iteration, use text after current closing % and next %
365 else if(value != null)
366 textLen = off1 - oldOff2 - 1;
367 // If value not found in current iteration, but a % was found for next iteration,
368 // use text from current closing % to the next %.
370 textLen = off1 - oldOff2;
371 if(off1 >= oldOff2 || off1 == -1)
372 result.Append (name, oldOff2+1, textLen);
373 } while (off2 > -1 && off2 < len);
375 return result.ToString ();
380 /// Return an array of the command line arguments of the current process
382 [MethodImplAttribute (MethodImplOptions.InternalCall)]
383 [EnvironmentPermissionAttribute (SecurityAction.Demand, Read = "PATH")]
384 public extern static string[] GetCommandLineArgs ();
386 [MethodImplAttribute (MethodImplOptions.InternalCall)]
387 internal extern static string internalGetEnvironmentVariable (string variable);
390 /// Return a string containing the value of the environment
391 /// variable identifed by parameter "variable"
393 public static string GetEnvironmentVariable (string variable)
396 if (SecurityManager.SecurityEnabled) {
397 new EnvironmentPermission (EnvironmentPermissionAccess.Read, variable).Demand ();
400 return internalGetEnvironmentVariable (variable);
403 static Hashtable GetEnvironmentVariablesNoCase ()
405 Hashtable vars = new Hashtable (CaseInsensitiveHashCodeProvider.Default,
406 CaseInsensitiveComparer.Default);
408 foreach (string name in GetEnvironmentVariableNames ()) {
409 vars [name] = internalGetEnvironmentVariable (name);
416 /// Return a set of all environment variables and their values
419 public static IDictionary GetEnvironmentVariables ()
421 StringBuilder sb = null;
422 if (SecurityManager.SecurityEnabled) {
423 // we must have access to each variable to get the lot
424 sb = new StringBuilder ();
425 // but (performance-wise) we do not want a stack-walk
426 // for each of them so we concatenate them
429 Hashtable vars = new Hashtable ();
430 foreach (string name in GetEnvironmentVariableNames ()) {
431 vars [name] = internalGetEnvironmentVariable (name);
439 new EnvironmentPermission (EnvironmentPermissionAccess.Read, sb.ToString ()).Demand ();
444 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
445 public static IDictionary GetEnvironmentVariables ()
447 Hashtable vars = new Hashtable ();
448 foreach (string name in GetEnvironmentVariableNames ()) {
449 vars [name] = internalGetEnvironmentVariable (name);
455 [MethodImplAttribute (MethodImplOptions.InternalCall)]
456 private extern static string GetWindowsFolderPath (int folder);
459 /// Returns the fully qualified path of the
460 /// folder specified by the "folder" parameter
462 public static string GetFolderPath (SpecialFolder folder)
464 return GetFolderPath (folder, SpecialFolderOption.None);
467 [MonoTODO ("Figure out the folder path for all the new values in SpecialFolder. Use the 'option' argument.")]
470 static string GetFolderPath(SpecialFolder folder, SpecialFolderOption option)
472 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
476 if (Environment.IsRunningOnWindows) {
477 dir = GetWindowsFolderPath ((int) folder);
479 dir = InternalGetFolderPath (folder);
482 if ((dir != null) && (dir.Length > 0) && SecurityManager.SecurityEnabled) {
483 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dir).Demand ();
489 private static string ReadXdgUserDir (string config_dir, string home_dir,
490 string key, string fallback)
492 string env_path = internalGetEnvironmentVariable (key);
493 if (env_path != null && env_path != String.Empty) {
497 string user_dirs_path = Path.Combine (config_dir, "user-dirs.dirs");
499 if (!File.Exists (user_dirs_path)) {
500 return Path.Combine (home_dir, fallback);
504 using(StreamReader reader = new StreamReader (user_dirs_path)) {
506 while ((line = reader.ReadLine ()) != null) {
508 int delim_index = line.IndexOf ('=');
509 if(delim_index > 8 && line.Substring (0, delim_index) == key) {
510 string path = line.Substring (delim_index + 1).Trim ('"');
511 bool relative = false;
513 if (path.StartsWith ("$HOME/")) {
515 path = path.Substring (6);
516 } else if (!path.StartsWith ("/")) {
520 return relative ? Path.Combine (home_dir, path) : path;
524 } catch (FileNotFoundException) {
527 return Path.Combine (home_dir, fallback);
531 // the security runtime (and maybe other parts of corlib) needs the
532 // information to initialize themselves before permissions can be checked
533 internal static string InternalGetFolderPath (SpecialFolder folder)
535 string home = internalGetHome ();
537 // http://freedesktop.org/Standards/basedir-spec/basedir-spec-0.6.html
539 // note: skip security check for environment variables
540 string data = internalGetEnvironmentVariable ("XDG_DATA_HOME");
541 if ((data == null) || (data == String.Empty)) {
542 data = Path.Combine (home, ".local");
543 data = Path.Combine (data, "share");
546 // note: skip security check for environment variables
547 string config = internalGetEnvironmentVariable ("XDG_CONFIG_HOME");
548 if ((config == null) || (config == String.Empty)) {
549 config = Path.Combine (home, ".config");
553 // MyComputer is a virtual directory
554 case SpecialFolder.MyComputer:
558 case SpecialFolder.Personal:
560 return Path.Combine (home, "Documents");
564 // use FDO's CONFIG_HOME. This data will be synced across a network like the windows counterpart.
565 case SpecialFolder.ApplicationData:
568 string dir = Path.Combine (Path.Combine (home, "Documents"), ".config");
569 if (!Directory.Exists (dir))
570 Directory.CreateDirectory (dir);
577 //use FDO's DATA_HOME. This is *NOT* synced
578 case SpecialFolder.LocalApplicationData:
581 string dir = Path.Combine (home, "Documents");
582 if (!Directory.Exists (dir))
583 Directory.CreateDirectory (dir);
591 case SpecialFolder.Desktop:
592 case SpecialFolder.DesktopDirectory:
593 return ReadXdgUserDir (config, home, "XDG_DESKTOP_DIR", "Desktop");
595 case SpecialFolder.MyMusic:
596 return ReadXdgUserDir (config, home, "XDG_MUSIC_DIR", "Music");
598 case SpecialFolder.MyPictures:
599 return ReadXdgUserDir (config, home, "XDG_PICTURES_DIR", "Pictures");
601 // these simply dont exist on Linux
602 // The spec says if a folder doesnt exist, we
604 case SpecialFolder.Favorites:
605 case SpecialFolder.Programs:
606 case SpecialFolder.SendTo:
607 case SpecialFolder.StartMenu:
608 case SpecialFolder.Startup:
609 case SpecialFolder.Templates:
610 case SpecialFolder.Cookies:
611 case SpecialFolder.History:
612 case SpecialFolder.InternetCache:
613 case SpecialFolder.Recent:
614 case SpecialFolder.CommonProgramFiles:
615 case SpecialFolder.ProgramFiles:
616 case SpecialFolder.System:
618 // This is where data common to all users goes
619 case SpecialFolder.CommonApplicationData:
622 throw new ArgumentException ("Invalid SpecialFolder");
626 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
627 public static string[] GetLogicalDrives ()
629 return GetLogicalDrivesInternal ();
633 [MethodImplAttribute (MethodImplOptions.InternalCall)]
634 private static extern void internalBroadcastSettingChange ();
636 public static string GetEnvironmentVariable (string variable, EnvironmentVariableTarget target)
639 case EnvironmentVariableTarget.Process:
640 return GetEnvironmentVariable (variable);
641 case EnvironmentVariableTarget.Machine:
642 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
643 if (!IsRunningOnWindows)
645 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")) {
646 object regvalue = env.GetValue (variable);
647 return (regvalue == null) ? null : regvalue.ToString ();
649 case EnvironmentVariableTarget.User:
650 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
651 if (!IsRunningOnWindows)
653 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.CurrentUser.OpenSubKey ("Environment", false)) {
654 object regvalue = env.GetValue (variable);
655 return (regvalue == null) ? null : regvalue.ToString ();
658 throw new ArgumentException ("target");
662 public static IDictionary GetEnvironmentVariables (EnvironmentVariableTarget target)
664 IDictionary variables = (IDictionary)new Hashtable ();
666 case EnvironmentVariableTarget.Process:
667 variables = GetEnvironmentVariables ();
669 case EnvironmentVariableTarget.Machine:
670 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
671 if (IsRunningOnWindows) {
672 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")) {
673 string[] value_names = env.GetValueNames ();
674 foreach (string value_name in value_names)
675 variables.Add (value_name, env.GetValue (value_name));
679 case EnvironmentVariableTarget.User:
680 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
681 if (IsRunningOnWindows) {
682 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.CurrentUser.OpenSubKey ("Environment")) {
683 string[] value_names = env.GetValueNames ();
684 foreach (string value_name in value_names)
685 variables.Add (value_name, env.GetValue (value_name));
690 throw new ArgumentException ("target");
695 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
696 public static void SetEnvironmentVariable (string variable, string value)
698 SetEnvironmentVariable (variable, value, EnvironmentVariableTarget.Process);
701 [EnvironmentPermission (SecurityAction.Demand, Unrestricted = true)]
702 public static void SetEnvironmentVariable (string variable, string value, EnvironmentVariableTarget target)
704 if (variable == null)
705 throw new ArgumentNullException ("variable");
706 if (variable == String.Empty)
707 throw new ArgumentException ("String cannot be of zero length.", "variable");
708 if (variable.IndexOf ('=') != -1)
709 throw new ArgumentException ("Environment variable name cannot contain an equal character.", "variable");
710 if (variable[0] == '\0')
711 throw new ArgumentException ("The first char in the string is the null character.", "variable");
714 case EnvironmentVariableTarget.Process:
715 InternalSetEnvironmentVariable (variable, value);
717 case EnvironmentVariableTarget.Machine:
718 if (!IsRunningOnWindows)
720 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true)) {
721 if (String.IsNullOrEmpty (value))
722 env.DeleteValue (variable, false);
724 env.SetValue (variable, value);
725 internalBroadcastSettingChange ();
728 case EnvironmentVariableTarget.User:
729 if (!IsRunningOnWindows)
731 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.CurrentUser.OpenSubKey ("Environment", true)) {
732 if (String.IsNullOrEmpty (value))
733 env.DeleteValue (variable, false);
735 env.SetValue (variable, value);
736 internalBroadcastSettingChange ();
740 throw new ArgumentException ("target");
744 [MethodImplAttribute (MethodImplOptions.InternalCall)]
745 internal static extern void InternalSetEnvironmentVariable (string variable, string value);
747 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode=true)]
748 public static void FailFast (string message)
750 throw new NotImplementedException ();
753 #if NET_4_0 || MOONLIGHT
755 public static void FailFast (string message, Exception exception)
757 throw new NotImplementedException ();
762 public static bool Is64BitOperatingSystem {
763 get { return IntPtr.Size == 8; } // FIXME: is this good enough?
766 public static bool Is64BitProcess {
767 get { return Is64BitOperatingSystem; }
770 public static int SystemPageSize {
771 get { return GetPageSize (); }
775 public static extern int ProcessorCount {
776 [EnvironmentPermission (SecurityAction.Demand, Read="NUMBER_OF_PROCESSORS")]
777 [MethodImplAttribute (MethodImplOptions.InternalCall)]
783 internal static bool IsRunningOnWindows {
784 get { return ((int) Platform < 4); }
788 // Used by gacutil.exe
790 #pragma warning disable 169
791 private static string GacPath {
793 if (Environment.IsRunningOnWindows) {
794 /* On windows, we don't know the path where mscorlib.dll will be installed */
795 string corlibDir = new DirectoryInfo (Path.GetDirectoryName (typeof (int).Assembly.Location)).Parent.Parent.FullName;
796 return Path.Combine (Path.Combine (corlibDir, "mono"), "gac");
799 return Path.Combine (Path.Combine (internalGetGacPath (), "mono"), "gac");
802 #pragma warning restore 169
803 [MethodImplAttribute (MethodImplOptions.InternalCall)]
804 internal extern static string internalGetGacPath ();
806 [MethodImplAttribute (MethodImplOptions.InternalCall)]
807 private extern static string [] GetLogicalDrivesInternal ();
809 [MethodImplAttribute (MethodImplOptions.InternalCall)]
810 private extern static string [] GetEnvironmentVariableNames ();
812 [MethodImplAttribute (MethodImplOptions.InternalCall)]
813 internal extern static string GetMachineConfigPath ();
815 [MethodImplAttribute (MethodImplOptions.InternalCall)]
816 internal extern static string internalGetHome ();
818 [MethodImplAttribute (MethodImplOptions.InternalCall)]
819 internal extern static int GetPageSize ();
821 static internal bool IsUnix {
823 int platform = (int) Environment.Platform;
825 return (platform == 4 || platform == 128 || platform == 6);