aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.Common/SystemInterop/StdErrAdapter.cs
blob: efb1421843c765506520af3a24aa70487bd115da (plain) (blame)
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
using Ryujinx.Common.Logging;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;

namespace Ryujinx.Common.SystemInterop
{
    public partial class StdErrAdapter : IDisposable
    {
        private bool _disposable = false;
        private UnixStream _pipeReader;
        private UnixStream _pipeWriter;
        private Thread _worker;

        public StdErrAdapter()
        {
            if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
            {
                RegisterPosix();
            }
        }

        [SupportedOSPlatform("linux")]
        [SupportedOSPlatform("macos")]
        private void RegisterPosix()
        {
            const int stdErrFileno = 2;

            (int readFd, int writeFd) = MakePipe();
            dup2(writeFd, stdErrFileno);

            _pipeReader = new UnixStream(readFd);
            _pipeWriter = new UnixStream(writeFd);

            _worker = new Thread(EventWorker);
            _disposable = true;
            _worker.Start();
        }

        [SupportedOSPlatform("linux")]
        [SupportedOSPlatform("macos")]
        private void EventWorker()
        {
            TextReader reader = new StreamReader(_pipeReader);
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Logger.Error?.PrintRawMsg(line);
            }
        }

        private void Dispose(bool disposing)
        {
            if (_disposable)
            {
                if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
                {
                    _pipeReader?.Close();
                    _pipeWriter?.Close();
                }

                _disposable = false;
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }

        [LibraryImport("libc", SetLastError = true)]
        private static partial int dup2(int fd, int fd2);

        [LibraryImport("libc", SetLastError = true)]
        private static unsafe partial int pipe(int* pipefd);

        private static unsafe (int, int) MakePipe()
        {
            int *pipefd = stackalloc int[2];

            if (pipe(pipefd) == 0)
            {
                return (pipefd[0], pipefd[1]);
            }
            else
            {
                throw new();
            }
        }
    }
}