示例#1
0
    // 初期化
    static Env()
    {
        BootTime = DateTimeOffset.Now;

        NumCpus = Math.Max(Environment.ProcessorCount, 1);

        int debugChecker = 0;

        Debug.Assert((++debugChecker) >= 1);
        Env.IsCoresLibraryDebugBuild = (debugChecker >= 1);

        CoresBasicLibAssembly = typeof(Env).Assembly;

        BuildTimeStamp = GetAssemblyBuildDate(CoresBasicLibAssembly);

        ExeAssembly = Assembly.GetExecutingAssembly();
        var asmName = ExeAssembly.GetName();

        ExeAssemblySimpleName = asmName.Name ?? throw new ArgumentNullException();
        ExeAssemblyFullName   = asmName.FullName;

        FrameworkVersion = Environment.Version;
        IsDotNetCore     = true;
        OsInfo           = EnvFastOsInfo.OsInfo;
        IsWindows        = EnvFastOsInfo.IsWindows;
        if (IsUnix)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                IsLinux = true;
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                IsMac = true;
            }

            UnixApi.InitUnixLimitsValue(IsMac, (IntPtr.Size == 8));
        }
        WindowsFamily = EnvFastOsInfo.WindowsFamily;

        IsOnGitHubActions = Environment.GetEnvironmentVariable("GITHUB_WORKFLOW")._IsFilled();

        PathSeparator = "" + Path.DirectorySeparatorChar;
        if (Str.IsEmptyStr(PathSeparator))
        {
            PathSeparator = "/";
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                PathSeparator = "\\";
            }
        }
        PathSeparatorChar         = PathSeparator[0];
        AppRealProcessExeFileName = IO.RemoveLastEnMark(GetAppRealProcessExeFileNameInternal());

        try
        {
            AppExecutableExeOrDllFileName = IO.RemoveLastEnMark(GetAppExeOrDllImageFilePathInternal());

            if (AppExecutableExeOrDllFileName._IsSamei("<Unknown>"))
            {
                // .NET 6.0 で single file にしている場合は、何と "<Unknown>" という文字列が戻ってくる。
                // しかし、single file であることはこれで分かるので、AppExecutableExeOrDllFileName を AppRealProcessExeFileName のコピーとする。
                AppExecutableExeOrDllFileName = AppRealProcessExeFileName;
            }
        }
        catch (FileNotFoundException)
        {
            // .NET 5.0 で、single file にしている場合は、何と FileNotFoundException が発生する。
            // しかし、single file であることはこれで分かるので、AppExecutableExeOrDllFileName を AppRealProcessExeFileName のコピーとする。
            AppExecutableExeOrDllFileName = AppRealProcessExeFileName;
        }

        BuildConfigurationName = GetBuildConfigurationNameInternal();

        // dotnet プロセスによって起動されたプロセスであるか否かを判別

        // .NET Core 2.2 以前は以下の方法で判別できる
        Env.IsHostedByDotNetProcess = Path.GetFileNameWithoutExtension(Env.AppRealProcessExeFileName).Equals("dotnet", StringComparison.OrdinalIgnoreCase);

        if (Env.IsHostedByDotNetProcess)
        {
            Env.DotNetHostProcessExeName = Process.GetCurrentProcess().MainModule !.FileName !;
        }
        else
        {
示例#2
0
        // 初期化
        static Env()
        {
            BootTime = DateTimeOffset.Now;

            NumCpus = Math.Max(Environment.ProcessorCount, 1);

            int debugChecker = 0;

            Debug.Assert((++debugChecker) >= 1);
            Env.IsCoresLibraryDebugBuild = (debugChecker >= 1);

            ExeAssembly = Assembly.GetExecutingAssembly();
            var asmName = ExeAssembly.GetName();

            ExeAssemblySimpleName = asmName.Name ?? throw new ArgumentNullException();
            ExeAssemblyFullName   = asmName.FullName;

            FrameworkVersion = Environment.Version;
            if (FrameworkInfoString.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase))
            {
                IsDotNetCore = true;
            }
            OsInfo    = Environment.OSVersion;
            IsWindows = (OsInfo.Platform == PlatformID.Win32NT);
            if (IsUnix)
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    IsLinux = true;
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    IsMac = true;
                }
            }

            PathSeparator = "" + Path.DirectorySeparatorChar;
            if (Str.IsEmptyStr(PathSeparator))
            {
                PathSeparator = "/";
                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    PathSeparator = "\\";
                }
            }
            PathSeparatorChar             = PathSeparator[0];
            AppRealProcessExeFileName     = IO.RemoveLastEnMark(GetAppRealProcessExeFileNameInternal());
            AppExecutableExeOrDllFileName = IO.RemoveLastEnMark(GetAppExeOrDllImageFilePathInternal());
            BuildConfigurationName        = GetBuildConfigurationNameInternal();

            // dotnet プロセスによって起動されたプロセスであるか否かを判別

            // .NET Core 2.2 以前は以下の方法で判別できる
            Env.IsHostedByDotNetProcess = Path.GetFileNameWithoutExtension(Env.AppRealProcessExeFileName).Equals("dotnet", StringComparison.OrdinalIgnoreCase);

            if (Env.IsHostedByDotNetProcess)
            {
                Env.DotNetHostProcessExeName = Process.GetCurrentProcess().MainModule.FileName;
            }
            else
            {
                // .NET Core 3.0 以降はスタンドアロンプロセスモードでも起動できるようになった
                // この場合は、
                // 1. DOTNET_ROOT 環境変数にディレクトリ名が入っていること
                // 2. DOTNET_ROOT 環境変数 + "\dotnet" というファイル (dotnet の実行可能ファイルである) が存在すること
                // で判定を行なう
                // (TODO: Windows ではこの方法で判別ができない)

                if (IsUnix)
                {
                    string?dotNetRoot = Environment.GetEnvironmentVariable("DOTNET_ROOT");

                    if (dotNetRoot._IsFilled())
                    {
                        if (Directory.Exists(dotNetRoot))
                        {
                            string dotnetExeName = Path.Combine(dotNetRoot, "dotnet");

                            if (File.Exists(dotnetExeName))
                            {
                                // 判定成功
                                Env.IsHostedByDotNetProcess  = true;
                                Env.DotNetHostProcessExeName = dotnetExeName;
                            }
                        }
                    }
                }
            }

            // DNS ホスト名とドメイン名の取得
            PalHostNetInfo.GetHostNameAndDomainNameInfo(out string dnsHostName, out string dnsDomainName);

            DnsHostName     = dnsHostName;
            DnsDomainName   = dnsDomainName;
            DnsFqdnHostName = DnsHostName + (string.IsNullOrEmpty(DnsDomainName) ? "" : "." + DnsDomainName);

            if (Str.IsEmptyStr(AppExecutableExeOrDllFileName) == false)
            {
                AppRootDir = AppExecutableExeOrDllFileDir = IO.RemoveLastEnMark(System.AppContext.BaseDirectory);
                // プログラムのあるディレクトリから 1 つずつ遡ってアプリケーションの root ディレクトリを取得する
                string tmp = AppExecutableExeOrDllFileDir;

                string tmp2 = AppExecutableExeOrDllFileDir._ReplaceStr("\\", "/");
                if (tmp2._InStr("/tmp/.net/", true) || tmp2._InStr("/temp/.net/", true))
                {
                    // dotnet publish で -p:PublishSingleFile=true で生成されたファイルである。
                    // この場合、AppExecutableExeOrDllFileDir は一時ディレクトリを指しているので、
                    // AppRootDir は代わりに EXE ファイルのある本物のディレクトリを指すようにする。
                    AppRootDir = tmp = Path.GetDirectoryName(AppRealProcessExeFileName) ?? AppRootDir;
                }

                IEnumerable <string> markerFiles = Env.IsHostedByDotNetProcess ? Consts.FileNames.AppRootMarkerFileNames : Consts.FileNames.AppRootMarkerFileNamesForBinary;

                while (true)
                {
                    try
                    {
                        bool found = false;

                        var filenames = Directory.GetFiles(tmp).Select(x => Path.GetFileName(x));

                        foreach (string fn in Consts.FileNames.AppRootMarkerFileNames)
                        {
                            if (filenames.Where(x => (IgnoreCaseTrim)x == fn).Any())
                            {
                                found = true;
                                break;
                            }

                            if (fn.StartsWith("."))
                            {
                                if (filenames.Where(x => x.EndsWith(fn, StringComparison.OrdinalIgnoreCase)).Any())
                                {
                                    found = true;
                                    break;
                                }
                            }
                        }

                        if (found)
                        {
                            AppRootDir = tmp;
                            break;
                        }
                        tmp = Path.GetDirectoryName(tmp) !;
                    }
                    catch
                    {
                        break;
                    }
                }
            }
            else
            {
                AppExecutableExeOrDllFileName = "/tmp/dummyexe";
                AppExecutableExeOrDllFileDir  = "/tmp";
                AppRootDir = IO.RemoveLastEnMark(Environment.CurrentDirectory);
            }

            HomeDir = IO.RemoveLastEnMark(Kernel.GetEnvStr("HOME"));
            if (Str.IsEmptyStr(HomeDir))
            {
                HomeDir = IO.RemoveLastEnMark(Kernel.GetEnvStr("HOMEDRIVE") + Kernel.GetEnvStr("HOMEPATH"));
            }
            if (Str.IsEmptyStr(HomeDir) == false)
            {
                UnixMutantDir = Path.Combine(HomeDir, ".dotnet_temp/.Cores.NET.Mutex");
            }
            else
            {
                HomeDir = AppRootDir;
                if (IsUnix)
                {
                    UnixMutantDir = Path.Combine("/tmp", ".dotnet_temp/.Cores.NET.Mutex");
                }
            }
            if (IsWindows)
            {
                UnixMutantDir = "";
            }
            if (Str.IsEmptyStr(UnixMutantDir) == false)
            {
                IO.MakeDirIfNotExists(UnixMutantDir);
            }
            if (IsWindows)
            {
                // Windows
                Win32_SystemDir  = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.System));
                Win32_WindowsDir = IO.RemoveLastEnMark(Path.GetDirectoryName(Win32_SystemDir) !);
                TempDir          = IO.RemoveLastEnMark(Path.GetTempPath());
                Win32_WinTempDir = IO.RemoveLastEnMark(Path.Combine(Win32_WindowsDir, "Temp"));
                IO.MakeDir(Win32_WinTempDir);
                if (Win32_WindowsDir.Length >= 2 && Win32_WindowsDir[1] == ':')
                {
                    Win32_WindowsDir = Win32_WindowsDir.Substring(0, 2).ToUpper();
                }
                else
                {
                    Win32_WindowsDrive = "C:";
                }
            }
            else
            {
                // UNIX
                Win32_SystemDir    = "/bin";
                Win32_WindowsDir   = "/bin";
                Win32_WindowsDrive = "/";
                if (Str.IsEmptyStr(HomeDir) == false)
                {
                    TempDir = Path.Combine(HomeDir, ".dotnet_temp/.Cores.NET.PerProcess.Temp");
                }
                else
                {
                    TempDir = "/tmp";
                }
                Win32_WinTempDir = TempDir;
            }
            FilePathStringComparer     = StrComparer.Get(!Env.IgnoreCaseInFileSystem);
            Win32_ProgramFilesDir      = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));
            Win32_PersonalStartMenuDir = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu));
            Win32_PersonalProgramsDir  = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.Programs));
            Win32_PersonalStartupDir   = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.Startup));
            Win32_PersonalAppDataDir   = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
            Win32_PersonalDesktopDir   = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
            Win32_MyDocumentsDir       = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
            Win32_LocalAppDataDir      = IO.RemoveLastEnMark(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
            if (IsUnix)
            {
                // ダミーディレクトリ
                Win32_SystemDir            = "/bin";
                Win32_WindowsDir           = "/bin";
                Win32_WindowsDrive         = "/";
                Win32_ProgramFilesDir      = "/bin";
                Win32_PersonalStartMenuDir = Path.Combine(HomeDir, "dummy/starmenu");
                Win32_PersonalProgramsDir  = Path.Combine(HomeDir, "dummy/starmenu/programs");
                Win32_PersonalStartupDir   = Path.Combine(HomeDir, "dummy/starmenu/startup");
                Win32_LocalAppDataDir      = Win32_PersonalAppDataDir = Path.Combine(HomeDir, ".dnappdata");
                Win32_PersonalDesktopDir   = Path.Combine(HomeDir, "dummy/desktop");
                Win32_MyDocumentsDir       = HomeDir;
            }
            StartupCurrentDir = CurrentDir;
            UserName          = Environment.UserName;
            try
            {
                UserNameEx = Environment.UserDomainName + "\\" + UserName;
            }
            catch
            {
                UserNameEx = UserName;
            }
            MachineName = Environment.MachineName;

            CommandLine = initCommandLine(Environment.CommandLine);

            IsLittleEndian = BitConverter.IsLittleEndian;
            ProcessId      = System.Diagnostics.Process.GetCurrentProcess().Id;
            IsAdmin        = CheckIsAdmin();

            if (IsUnix)
            {
                MutantUnixImpl.DeleteUnusedMutantFiles();
            }
        }