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 signature or
57 * semantics etc), 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 = 58;
64 public enum SpecialFolder
65 { // TODO: Determine if these windoze style folder identifiers
66 // have unix/linux counterparts
82 DesktopDirectory = 0x10,
84 ApplicationData = 0x1a,
85 LocalApplicationData = 0x1c,
89 CommonApplicationData = 0x23,
93 CommonProgramFiles = 0x2b,
97 /// Gets the command line for this process
99 public static string CommandLine {
100 // note: security demand inherited from calling GetCommandLineArgs
102 // FIXME: we may need to quote, but any sane person
103 // should use GetCommandLineArgs () instead.
104 return String.Join (" ", GetCommandLineArgs ());
109 /// Gets or sets the current directory. Actually this is supposed to get
110 /// and/or set the process start directory acording to the documentation
111 /// but actually test revealed at beta2 it is just Getting/Setting the CurrentDirectory
113 public static string CurrentDirectory
116 return Directory.GetCurrentDirectory ();
119 Directory.SetCurrentDirectory (value);
124 /// Gets or sets the exit code of this process
126 public extern static int ExitCode
128 [MethodImplAttribute (MethodImplOptions.InternalCall)]
130 [MethodImplAttribute (MethodImplOptions.InternalCall)]
137 public extern bool HasShutdownStarted
139 [MethodImplAttribute (MethodImplOptions.InternalCall)]
145 /// Gets the name of the local computer
147 public extern static string MachineName {
148 [MethodImplAttribute (MethodImplOptions.InternalCall)]
149 [EnvironmentPermission (SecurityAction.Demand, Read="COMPUTERNAME")]
150 [SecurityPermission (SecurityAction.Demand, UnmanagedCode=true)]
155 /// Gets the standard new line value
157 public extern static string NewLine {
158 [MethodImplAttribute (MethodImplOptions.InternalCall)]
163 // Support methods and fields for OSVersion property
165 static OperatingSystem os;
167 internal static extern PlatformID Platform {
168 [MethodImplAttribute (MethodImplOptions.InternalCall)]
172 [MethodImplAttribute (MethodImplOptions.InternalCall)]
173 internal static extern string GetOSVersionString ();
176 /// Gets the current OS version information
178 public static OperatingSystem OSVersion {
181 Version v = Version.CreateFromString (GetOSVersionString ());
182 PlatformID p = Platform;
187 os = new OperatingSystem (p, v);
196 public static string StackTrace {
197 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
199 System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace (0, true);
200 return trace.ToString ();
205 /// Get a fully qualified path to the system directory
207 public static string SystemDirectory {
209 return GetFolderPath (SpecialFolder.System);
214 /// Get the number of milliseconds that have elapsed since the system was booted
216 public extern static int TickCount {
217 [MethodImplAttribute (MethodImplOptions.InternalCall)]
222 /// Get UserDomainName
224 public static string UserDomainName {
225 // FIXME: this variable doesn't exist (at least not on WinXP) - reported to MS as FDBK20562
226 [EnvironmentPermission (SecurityAction.Demand, Read="USERDOMAINNAME")]
233 /// Gets a flag indicating whether the process is in interactive mode
235 [MonoTODO ("Currently always returns false, regardless of interactive state")]
236 public static bool UserInteractive {
243 /// Get the user name of current process is running under
245 public extern static string UserName {
246 [MethodImplAttribute (MethodImplOptions.InternalCall)]
247 [EnvironmentPermission (SecurityAction.Demand, Read="USERNAME;USER")]
252 /// Get the version of the common language runtime
254 public static Version Version {
256 return new Version (Consts.FxFileVersion);
261 /// Get the amount of physical memory mapped to process
263 [MonoTODO ("Currently always returns zero")]
264 public static long WorkingSet {
265 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
269 [MethodImplAttribute (MethodImplOptions.InternalCall)]
270 [SecurityPermission (SecurityAction.Demand, UnmanagedCode=true)]
271 public extern static void Exit (int exitCode);
274 /// Substitute environment variables in the argument "name"
276 public static string ExpandEnvironmentVariables (string name)
279 throw new ArgumentNullException ("name");
281 int off1 = name.IndexOf ('%');
285 int len = name.Length;
287 if (off1 == len - 1 || (off2 = name.IndexOf ('%', off1 + 1)) == -1)
290 StringBuilder result = new StringBuilder ();
291 result.Append (name, 0, off1);
292 Hashtable tbl = null;
294 string var = name.Substring (off1 + 1, off2 - off1 - 1);
295 string value = GetEnvironmentVariable (var);
296 if (value == null && Environment.IsRunningOnWindows) {
297 // On windows, env. vars. are case insensitive
299 tbl = GetEnvironmentVariablesNoCase ();
301 value = tbl [var] as string;
304 // If value not found, add %FOO to stream,
305 // and use the closing % for the next iteration.
306 // If value found, expand it in place of %FOO%
312 result.Append (value);
315 off1 = name.IndexOf ('%', off2 + 1);
316 // If no % found for off1, don't look for one for off2
317 off2 = (off1 == -1 || off2 > len-1)? -1 :name.IndexOf ('%', off1 + 1);
318 // textLen is the length of text between the closing % of current iteration
319 // and the starting % of the next iteration if any. This text is added to output
321 // If no new % found, use all the remaining text
322 if (off1 == -1 || off2 == -1)
323 textLen = len - oldOff2 - 1;
324 // If value found in current iteration, use text after current closing % and next %
325 else if(value != null)
326 textLen = off1 - oldOff2 - 1;
327 // If value not found in current iteration, but a % was found for next iteration,
328 // use text from current closing % to the next %.
330 textLen = off1 - oldOff2;
331 if(off1 >= oldOff2 || off1 == -1)
332 result.Append (name, oldOff2+1, textLen);
333 } while (off2 > -1 && off2 < len);
335 return result.ToString ();
340 /// Return an array of the command line arguments of the current process
342 [MethodImplAttribute (MethodImplOptions.InternalCall)]
343 [EnvironmentPermissionAttribute (SecurityAction.Demand, Read = "PATH")]
344 public extern static string[] GetCommandLineArgs ();
346 [MethodImplAttribute (MethodImplOptions.InternalCall)]
347 internal extern static string internalGetEnvironmentVariable (string name);
350 /// Return a string containing the value of the environment
351 /// variable identifed by parameter "variable"
353 public static string GetEnvironmentVariable (string name)
355 if (SecurityManager.SecurityEnabled) {
356 new EnvironmentPermission (EnvironmentPermissionAccess.Read, name).Demand ();
358 return internalGetEnvironmentVariable (name);
361 static Hashtable GetEnvironmentVariablesNoCase ()
363 Hashtable vars = new Hashtable (CaseInsensitiveHashCodeProvider.Default,
364 CaseInsensitiveComparer.Default);
366 foreach (string name in GetEnvironmentVariableNames ()) {
367 vars [name] = internalGetEnvironmentVariable (name);
374 /// Return a set of all environment variables and their values
377 public static IDictionary GetEnvironmentVariables ()
379 StringBuilder sb = null;
380 if (SecurityManager.SecurityEnabled) {
381 // we must have access to each variable to get the lot
382 sb = new StringBuilder ();
383 // but (performance-wise) we do not want a stack-walk
384 // for each of them so we concatenate them
387 Hashtable vars = new Hashtable ();
388 foreach (string name in GetEnvironmentVariableNames ()) {
389 vars [name] = internalGetEnvironmentVariable (name);
397 new EnvironmentPermission (EnvironmentPermissionAccess.Read, sb.ToString ()).Demand ();
402 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
403 public static IDictionary GetEnvironmentVariables ()
405 Hashtable vars = new Hashtable ();
406 foreach (string name in GetEnvironmentVariableNames ()) {
407 vars [name] = internalGetEnvironmentVariable (name);
413 [MethodImplAttribute (MethodImplOptions.InternalCall)]
414 private extern static string GetWindowsFolderPath (int folder);
417 /// Returns the fully qualified path of the
418 /// folder specified by the "folder" parameter
420 public static string GetFolderPath (SpecialFolder folder)
424 if (Environment.IsRunningOnWindows) {
425 dir = GetWindowsFolderPath ((int) folder);
427 dir = InternalGetFolderPath (folder);
430 if ((dir != null) && (dir.Length > 0) && SecurityManager.SecurityEnabled) {
431 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dir).Demand ();
436 private static string ReadXdgUserDir (string config_dir, string home_dir,
437 string key, string fallback)
439 string env_path = internalGetEnvironmentVariable (key);
440 if (env_path != null && env_path != String.Empty) {
444 string user_dirs_path = Path.Combine (config_dir, "user-dirs.dirs");
446 if (!File.Exists (user_dirs_path)) {
447 return Path.Combine (home_dir, fallback);
451 using(StreamReader reader = new StreamReader (user_dirs_path)) {
453 while ((line = reader.ReadLine ()) != null) {
455 int delim_index = line.IndexOf ('=');
456 if (delim_index > 8 && line.Substring (0, delim_index) == key) {
457 return Path.Combine (home_dir, line.Substring (delim_index + 1));
461 } catch (FileNotFoundException) {
464 return Path.Combine (home_dir, fallback);
468 // the security runtime (and maybe other parts of corlib) needs the
469 // information to initialize themselves before permissions can be checked
470 internal static string InternalGetFolderPath (SpecialFolder folder)
472 string home = internalGetHome ();
474 // http://freedesktop.org/Standards/basedir-spec/basedir-spec-0.6.html
476 // note: skip security check for environment variables
477 string data = internalGetEnvironmentVariable ("XDG_DATA_HOME");
478 if ((data == null) || (data == String.Empty)) {
479 data = Path.Combine (home, ".local");
480 data = Path.Combine (data, "share");
483 // note: skip security check for environment variables
484 string config = internalGetEnvironmentVariable ("XDG_CONFIG_HOME");
485 if ((config == null) || (config == String.Empty)) {
486 config = Path.Combine (home, ".config");
491 // MyComputer is a virtual directory
492 case SpecialFolder.MyComputer:
496 case SpecialFolder.Personal:
498 // use FDO's CONFIG_HOME. This data will be synced across a network like the windows counterpart.
499 case SpecialFolder.ApplicationData:
501 //use FDO's DATA_HOME. This is *NOT* synced
502 case SpecialFolder.LocalApplicationData:
505 case SpecialFolder.Desktop:
507 case SpecialFolder.DesktopDirectory:
508 return ReadXdgUserDir (config, home, "XDG_DESKTOP_DIR", "Desktop");
510 case SpecialFolder.MyMusic:
511 return ReadXdgUserDir (config, home, "XDG_MUSIC_DIR", "Music");
513 case SpecialFolder.MyPictures:
514 return ReadXdgUserDir (config, home, "XDG_PICTURES_DIR", "Pictures");
516 // these simply dont exist on Linux
517 // The spec says if a folder doesnt exist, we
519 case SpecialFolder.Favorites:
520 case SpecialFolder.Programs:
521 case SpecialFolder.SendTo:
522 case SpecialFolder.StartMenu:
523 case SpecialFolder.Startup:
524 case SpecialFolder.Templates:
525 case SpecialFolder.Cookies:
526 case SpecialFolder.History:
527 case SpecialFolder.InternetCache:
528 case SpecialFolder.Recent:
529 case SpecialFolder.CommonProgramFiles:
530 case SpecialFolder.ProgramFiles:
531 case SpecialFolder.System:
533 // This is where data common to all users goes
534 case SpecialFolder.CommonApplicationData:
537 throw new ArgumentException ("Invalid SpecialFolder");
541 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
542 public static string[] GetLogicalDrives ()
544 return GetLogicalDrivesInternal ();
547 // FIXME: Anyone using this anywhere ?
548 static internal string GetResourceString (string s) { return String.Empty; }
552 public static string GetEnvironmentVariable (string variable, EnvironmentVariableTarget target)
555 case EnvironmentVariableTarget.Process:
556 return GetEnvironmentVariable (variable);
557 case EnvironmentVariableTarget.Machine:
558 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
559 if (!IsRunningOnWindows)
561 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")) {
562 return env.GetValue (variable).ToString ();
564 case EnvironmentVariableTarget.User:
565 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
566 if (!IsRunningOnWindows)
568 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.CurrentUser.OpenSubKey ("Environment", false)) {
569 return env.GetValue (variable).ToString ();
572 throw new ArgumentException ("target");
576 public static IDictionary GetEnvironmentVariables (EnvironmentVariableTarget target)
578 IDictionary variables = (IDictionary)new Hashtable ();
580 case EnvironmentVariableTarget.Process:
581 variables = GetEnvironmentVariables ();
583 case EnvironmentVariableTarget.Machine:
584 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
585 if (IsRunningOnWindows) {
586 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")) {
587 string[] value_names = env.GetValueNames ();
588 foreach (string value_name in value_names)
589 variables.Add (value_name, env.GetValue (value_name));
593 case EnvironmentVariableTarget.User:
594 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
595 if (IsRunningOnWindows) {
596 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.CurrentUser.OpenSubKey ("Environment")) {
597 string[] value_names = env.GetValueNames ();
598 foreach (string value_name in value_names)
599 variables.Add (value_name, env.GetValue (value_name));
604 throw new ArgumentException ("target");
609 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
610 public static void SetEnvironmentVariable (string variable, string value)
612 SetEnvironmentVariable (variable, value, EnvironmentVariableTarget.Process);
615 [EnvironmentPermission (SecurityAction.Demand, Unrestricted = true)]
616 public static void SetEnvironmentVariable (string variable, string value, EnvironmentVariableTarget target)
618 if (variable == null)
619 throw new ArgumentNullException ("variable");
620 if (variable == String.Empty)
621 throw new ArgumentException ("String cannot be of zero length.", "variable");
622 if (variable.IndexOf ('=') != -1)
623 throw new ArgumentException ("Environment variable name cannot contain an equal character.", "variable");
624 if (variable[0] == '\0')
625 throw new ArgumentException ("The first char in the string is the null character.", "variable");
628 case EnvironmentVariableTarget.Process:
629 InternalSetEnvironmentVariable (variable, value);
631 case EnvironmentVariableTarget.Machine:
632 if (!IsRunningOnWindows)
634 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true)) {
635 if (value == null || value.Length == 0)
636 env.DeleteValue (variable, false);
638 env.SetValue (variable, value);
641 case EnvironmentVariableTarget.User:
642 if (!IsRunningOnWindows)
644 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.CurrentUser.OpenSubKey ("Environment", true)) {
645 if (value == null || value.Length == 0)
646 env.DeleteValue (variable, false);
648 env.SetValue (variable, value);
652 throw new ArgumentException ("target");
656 [MethodImplAttribute (MethodImplOptions.InternalCall)]
657 internal static extern void InternalSetEnvironmentVariable (string variable, string value);
659 public static extern int ProcessorCount {
660 [EnvironmentPermission (SecurityAction.Demand, Read="NUMBER_OF_PROCESSORS")]
661 [MethodImplAttribute (MethodImplOptions.InternalCall)]
665 [MonoTODO ("Not implemented")]
666 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode=true)]
667 public static void FailFast (string message)
669 throw new NotImplementedException ();
675 internal static bool IsRunningOnWindows {
676 get { return ((int) Platform != 128); }
679 private static string GacPath {
681 if (Environment.IsRunningOnWindows) {
682 /* On windows, we don't know the path where mscorlib.dll will be installed */
683 string corlibDir = new DirectoryInfo (Path.GetDirectoryName (typeof (int).Assembly.Location)).Parent.Parent.FullName;
684 return Path.Combine (Path.Combine (corlibDir, "mono"), "gac");
687 return Path.Combine (Path.Combine (internalGetGacPath (), "mono"), "gac");
691 [MethodImplAttribute (MethodImplOptions.InternalCall)]
692 private extern static string [] GetLogicalDrivesInternal ();
694 [MethodImplAttribute (MethodImplOptions.InternalCall)]
695 private extern static string [] GetEnvironmentVariableNames ();
697 [MethodImplAttribute (MethodImplOptions.InternalCall)]
698 internal extern static string GetMachineConfigPath ();
700 [MethodImplAttribute (MethodImplOptions.InternalCall)]
701 internal extern static string internalGetGacPath ();
703 [MethodImplAttribute (MethodImplOptions.InternalCall)]
704 internal extern static string internalGetHome ();