public override int Write(ReadOnlySpan <byte> path, ulong off, ReadOnlySpan <byte> buffer, ref FuseFileInfo fi, Guid fileGuid)
        {
            path = base.TransformPath(path);

            if (debug)
            {
                Console.WriteLine($"NeoFS::Write()");
            }
            if (fi.fh == 0)
            {
                var newFd = LibC.open(toBp(path), fi.flags);
                if (newFd > 0)
                {
                    fi.fh = (ulong)newFd;
                }
                else
                {
                    return(-LibC.errno);
                }
            }

            ssize_t res;

            fixed(void *vbuf = buffer)
            {
                res = LibC.pwrite((int)fi.fh, vbuf, buffer.Length, (long)off);
            }

            if (res < 0)
            {
                return(-LibC.errno);
            }

            return((int)res);
        }
Beispiel #2
0
        private void TransmitLoop(CancellationToken token)
        {
            while (true)
            {
                byte[] buffer = null;
                if (stream == null)
                {
                    return;
                }
                try
                {
                    buffer = LibC.ReadDataWithTimeout(stream.Handle, MTU, 1000, () => token.IsCancellationRequested);
                }
                catch (ArgumentException)
                {
                    // stream was closed
                    return;
                }
                catch (ObjectDisposedException)
                {
                    return;
                }

                if (token.IsCancellationRequested)
                {
                    return;
                }
                if (buffer == null || buffer.Length == 0)
                {
                    continue;
                }
                var ethernetFrame = EthernetFrame.CreateEthernetFrameWithCRC(buffer);
                FrameReady?.Invoke(ethernetFrame);
            }
        }
Beispiel #3
0
        internal static int Read(int fd, ulong offset, Span <byte> buffer)
        {
            if (fd == -1)
            {
                return(LibC.EACCES);
            }

            LibC.lseek(fd, (long)offset, LibC.SEEK_SET);
            if (LibC.errno != 0)
            {
                return(-LibC.errno);
            }

            ssize_t rd;

            fixed(void *bp = buffer)
            {
                rd = LibC.read(fd, bp, buffer.Length);
            }

            if (rd >= 0)
            {
                return((int)rd);
            }

            return(-LibC.errno);
        }
Beispiel #4
0
        /// <summary>
        /// allocate size bytes starting at a particular address
        /// </summary>
        /// <param name="start"></param>
        /// <param name="size"></param>
        public MemoryBlock(ulong start, ulong size)
        {
#if !MONO
            Start = (ulong)Kernel32.VirtualAlloc(Z.UU(start), Z.UU(size),
                                                 Kernel32.AllocationType.RESERVE | Kernel32.AllocationType.COMMIT,
                                                 Kernel32.MemoryProtection.NOACCESS);
            if (Start == 0)
            {
                throw new InvalidOperationException("VirtualAlloc() returned NULL");
            }
            if (start != 0)
            {
                End = start + size;
            }
            else
            {
                End = Start + size;
            }
            Size = End - Start;
#else
            Start = (ulong)LibC.mmap(ZC.U(start), ZC.U(size), 0, LibC.MapType.MAP_ANONYMOUS, -1, IntPtr.Zero);
            if (Start == 0)
            {
                throw new InvalidOperationException("mmap() returned NULL");
            }
            End  = Start + size;
            Size = End - Start;
#endif
        }
        public override void Release(ReadOnlySpan <byte> path, ref FuseFileInfo fi, Guid fileGuid)
        {
            path = base.TransformPath(path);

            if (debug)
            {
                Console.WriteLine($"NeoFS::Release({RawDirs.HR(path)})");
            }

            if (FileContexts.TryGetValue(fi.fh, out var context))
            {
                if (context.ExtAssetSha1 != null)  // Asset Mode
                {
                    base.AssetRelease(path, ref fi, fileGuid);
                }
                FileContexts.Remove(fi.fh);
            }

            if (fi.fh > 0)
            {
                LibC.close((int)fi.fh);
            }

            fi.fh = 0;
        }
        // Write
        public override int Create(ReadOnlySpan <byte> path, mode_t mode, ref FuseFileInfo fi, Guid fileGuid)
        {
            path = base.TransformPath(path);

            if (debug)
            {
                Console.WriteLine($"NeoFS::Create()");
            }

            fi.fh = 0;

            var res = LibC.open(toBp(path), fi.flags, mode);

            if (res < 0)
            {
                return(-LibC.errno);
            }

            fi.fh = (ulong)res;

            // Make these settable (these actually come in on the Init method, which TDMS isn't handling yet)
            var uid = (uid_t)10010;
            var gid = (gid_t)10010;

            res = LibC.chown(toBp(path), uid, gid);

            return(0);
        }
Beispiel #7
0
        /* public sBuffersSet allocateEncodedBuffers( int encodedBuffers, ref sPixelFormatMP format )
         * {
         *      sCreateBuffers buffers = new sCreateBuffers()
         *      {
         *              count = encodedBuffers,
         *              memory = eMemory.MemoryMap,
         *      };
         *      buffers.format.bufferType = eBufferType.VideoOutputMPlane;
         *      buffers.format.pix_mp = format;
         *      Logger.logVerbose( "allocateEncodedBuffers: {0} buffers\n{1}", encodedBuffers, format );
         *      file.call( eControlCode.CREATE_BUFS, ref buffers );
         *      return new sBuffersSet( buffers.index, buffers.count );
         * } */

        /* internal sBuffersSet allocateDecodedBuffers( int decodedBuffersCount, ref VideoTextureDesc desc, ref DmaBuffers dma )
         * {
         *      sCreateBuffers buffers = new sCreateBuffers()
         *      {
         *              count = decodedBuffersCount,
         *              memory = eMemory.MemoryMap,
         *      };
         *      buffers.format.bufferType = eBufferType.VideoCaptureMPlane;
         *
         *      sPixelFormatMP pf = default;
         *      pf.size = desc.lumaSize;
         *      pf.pixelFormat = ePixelFormat.NV12;
         *      pf.field = eField.Progressive;
         *      pf.numPlanes = 2;
         *
         *      sPlanePixelFormat ppf = default;
         *      ppf.bytesPerLine = dma.luma.stride;
         *      ppf.sizeImage = dma.luma.stride * desc.lumaSize.cy;
         *      pf.setPlaneFormat( 0, ppf );
         *
         *      ppf.bytesPerLine = dma.chroma.stride;
         *      ppf.sizeImage = dma.chroma.stride * desc.chromaSize.cy;
         *      pf.setPlaneFormat( 1, ppf );
         *
         *      buffers.format.pix_mp = pf;
         *      file.call( eControlCode.CREATE_BUFS, ref buffers );
         *      return new sBuffersSet( buffers.index, buffers.count );
         * } */

        public bool tryGetEvent(out sEvent evt)
        {
            int res;

            unsafe
            {
                fixed(sEvent *pointer = &evt)
                res = LibC.ioctl(file, (uint)eControlCode.DQEVENT, pointer);
            }
            if (0 == res)
            {
                // Got an event
                return(true);
            }
            // Got no event, check errno
            int errno = Marshal.GetLastWin32Error();

            if (errno == LibC.ENOENT)
            {
                // Undocumented behavior, BTW, kernel.org docs never say the "no events" condition generates ENOENT code.
                evt = default;
                return(false);
            }

            string message = NativeErrorMessages.lookupLinuxError(errno);

            if (null != message)
            {
                throw new COMException($"I/O control code DQEVENT failed: { message }", LibC.hresultFromLinux(errno));
            }
            throw new COMException($"I/O control code DQEVENT failed: undocumented Linux error code { errno }", LibC.hresultFromLinux(errno));
        }
        unsafe private void CallFstat()
        {
            LibC.stat fstats = new LibC.stat();

            int current_status = LibC._fstat(0, (int)fd.Value, &fstats);

            status.Value = (uint)current_status;
            if (current_status == -1)
            {
                SetErrorNumber();
            }

            st_dev.Value     = (uint)fstats.st_dev;
            st_ino.Value     = (uint)fstats.st_ino;
            st_mode.Value    = (uint)fstats.st_mode;
            st_nlink.Value   = (uint)fstats.st_nlink;
            st_uid.Value     = (uint)fstats.st_uid;
            st_gid.Value     = (uint)fstats.st_gid;
            st_size.Value    = (uint)fstats.st_size;
            st_rdev.Value    = (uint)fstats.st_rdev;
            st_blksize.Value = (uint)fstats.st_blksize;
            st_blocks.Value  = (uint)fstats.st_blocks;
            st_atim.Value    = (uint)fstats.st_atim.tv_sec;
            st_mtim.Value    = (uint)fstats.st_mtim.tv_sec;
            st_ctim.Value    = (uint)fstats.st_ctim.tv_sec;
            st_atim_ns.Value = (uint)fstats.st_atim.tv_nsec;
            st_mtim_ns.Value = (uint)fstats.st_mtim.tv_nsec;
            st_ctim_ns.Value = (uint)fstats.st_ctim.tv_nsec;

            call = Call.Done;
        }
Beispiel #9
0
        // private IEnumerator<string> pathStr(string )

        public unsafe int Create(FileDescriptor fds, mode_t mode, int flags)
        {
            Console.WriteLine($"[Cache-Create {Encoding.ASCII.GetString(fds.FileNode.Content.CacheFile)}]");

            var fileg = fds.FileNode.Content.CachePoolGuid.Value.ToString().ToLower();

            // Intermediate directories probably don't exist - this needs to be much smarter
            var ca1 = $"/ua/NeoVirtCache/{fileg.Substring(0, 3)}";
            //var ca2 = $"/ua/NeoVirtCache/{fileg.Substring(0, 2)}/{fileg.Substring(2, 2)}";
            //var ca3 = $"/ua/NeoVirtCache/{fileg.Substring(0, 2)}/{fileg.Substring(2, 2)}/{fileg.Substring(4, 2)}";
            //var ca4 = $"/ua/NeoVirtCache/{fileg.Substring(0, 2)}/{fileg.Substring(2, 2)}/{fileg.Substring(4, 2)}/{fileg.Substring(6, 2)}/";

            var ret = LibC.mkdir(toBp(Encoding.ASCII.GetBytes(ca1)), 0b111_101_000);

            //ret = LibC.mkdir(toBp(Encoding.ASCII.GetBytes(ca2)), 0b111_101_000);
            //ret = LibC.mkdir(toBp(Encoding.ASCII.GetBytes(ca3)), 0b111_101_000);
            //ret = LibC.mkdir(toBp(Encoding.ASCII.GetBytes(ca4)), 0b111_101_000);

            iot = LibC.open(toBp(fds.FileNode.Content.CacheFile), flags, 0b110_100_000);
            if (iot < 0)
            {
                return(iot);
            }

            return(0);
        }
Beispiel #10
0
        public static void poll(ReadOnlySpan <pollfd> waitHandles, out eDecoderBits decoderBits, out eAudioBits audio, out bool seekRequest, out bool shutdownRequest)
        {
            LibC.poll(waitHandles);
            decoderBits = (eDecoderBits)waitHandles[0].revents;
            audio       = (eAudioBits)waitHandles[1].revents;
            ePollEvents seek     = waitHandles[2].revents;
            ePollEvents shutdown = waitHandles[3].revents;

            if (decoderBits.HasFlag(eDecoderBits.Error))
            {
                throw new ApplicationException("poll(3) returned error status for the decoder device, probably the decoder failed");
            }
            if (audio.HasFlag(eAudioBits.Error))
            {
                throw new ApplicationException("poll(3) returned error status for the audio queue");
            }
            if (seek.HasFlag(ePollEvents.POLLERR))
            {
                throw new ApplicationException("poll(3) returned error status for the seek event handle");
            }
            if (shutdown.HasFlag(ePollEvents.POLLERR))
            {
                throw new ApplicationException("poll(3) returned error status for the shutdown event handle");
            }

            seekRequest     = seek.HasFlag(ePollEvents.POLLIN);
            shutdownRequest = shutdown.HasFlag(ePollEvents.POLLIN);
        }
Beispiel #11
0
        public unsafe static byte[] GetSha1(byte[] path)
        {
            var ps    = PenguinSanitizer.Extensions.ToBytePtr(path);
            var newFd = LibC.open(ps, LibC.O_RDONLY);

            // Tap the stream so we can get a hash on it.

            var hash = HashAlgorithm.Create("SHA1");

            var buf = new Byte[32 * 1024 * 1024];

            while (true)
            {
                ssize_t rd = 0;
                fixed(void *b = buf)
                {
                    rd = LibC.read(newFd, b, buf.Length);

                    hash.TransformBlock(buf, 0, (int)rd, buf, 0);
                }

                if (rd < 1)
                {
                    break;
                }
            }

            LibC.close(newFd);
            buf = null;

            hash.TransformFinalBlock(buf, 0, 0);
            return(hash.Hash);
        }
Beispiel #12
0
        protected override bool onVideoStreamTick(TimeSpan pendingVideoFrame)
        {
            audioPlayer.marshalException();
            if (isPaused)
            {
                return(false);
            }

            long clock = audioClock;

            if (clock < 0)
            {
                return(false);
            }

            if (pendingVideoFrame.Ticks > clock)
            {
                // The first of the pending video frames should be rendered in the future, in relation to the audio clock
                TimeSpan remainingTime = TimeSpan.FromTicks(pendingVideoFrame.Ticks - clock);
                if (remainingTime <= frameDuration)
                {
                    // The remaining time to wait is smaller than duration of the frame. Render now, it will take some time to do, and then it'll wait for vsync.
                    return(true);
                }

                // The remaining time to wait is longer than frame on the display.
                // Sleep for the correct amount of time, and then render.
                LibC.sleep(remainingTime - frameDuration);
                return(true);
            }
            // We're too late already, this video frame should have been rendered in the past.
            return(true);
        }
Beispiel #13
0
        public MemoryBlock(UIntPtr start, long size)
        {
#if !MONO
            Start = Kernel32.VirtualAlloc(start, checked ((UIntPtr)size),
                                          Kernel32.AllocationType.RESERVE | Kernel32.AllocationType.COMMIT,
                                          Kernel32.MemoryProtection.NOACCESS);
            if (Start == UIntPtr.Zero)
            {
                throw new InvalidOperationException("VirtualAlloc() returned NULL");
            }
            if (start != UIntPtr.Zero)
            {
                End = (UIntPtr)((long)start + size);
            }
            else
            {
                End = (UIntPtr)((long)Start + size);
            }
            Size = (long)End - (long)Start;
#else
            Start = LibC.mmap(start, checked ((UIntPtr)size), 0, LibC.MapType.MAP_ANONYMOUS, -1, IntPtr.Zero);
            if (Start == UIntPtr.Zero)
            {
                throw new InvalidOperationException("mmap() returned NULL");
            }
            End  = (UIntPtr)((long)Start + size);
            Size = (long)End - (long)Start;
#endif
        }
Beispiel #14
0
        public unsafe void LibraryNames()
        {
            var methods = typeof(LibC).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

            foreach (var method in methods)
            {
                DllImportAttribute dllImportAttribute = method.GetCustomAttribute <DllImportAttribute>();
                if (dllImportAttribute != null)
                {
                    string functionName = dllImportAttribute.EntryPoint;
                    string libName      = dllImportAttribute.Value;
                    IntPtr libHandle    = IntPtr.Zero;
                    lock (s_dlopened)
                    {
                        if (!s_dlopened.TryGetValue(libName, out libHandle))
                        {
                            fixed(byte *filename = Encoding.UTF8.GetBytes(libName))
                            {
                                libHandle = new IntPtr(LibC.dlopen(filename, LibC.RTLD_LAZY));
                            }

                            Assert.True(IntPtr.Zero != libHandle, $"Library not found: {libName}");
                            s_dlopened.Add(libName, libHandle);
                        }
                    }

                    fixed(byte *symbol = Encoding.UTF8.GetBytes(functionName))
                    {
                        IntPtr symbolHandle = new IntPtr(LibC.dlsym(libHandle.ToPointer(), symbol));

                        Assert.True(IntPtr.Zero != symbolHandle, $"Function symbol not found in {libName}: {functionName}");
                    }
                }
            }
        }
        public override int FAllocate(ReadOnlySpan <byte> path, int mode, ulong offset, long length, ref FuseFileInfo fi, Guid fileGuid)
        {
            path = base.TransformPath(path);

            if (debug)
            {
                Console.WriteLine($"NeoFS::FAllocate()");
            }

            if (fi.fh == 0)
            {
                var newFd = LibC.open(toBp(path), fi.flags);
                if (newFd > 0)
                {
                    fi.fh = (ulong)newFd;
                }
                else
                {
                    return(-LibC.errno);
                }
            }


            var res = LibC.fallocate((int)fi.fh, mode, (long)offset, length);


            if (res < 0)
            {
                return(-LibC.errno);
            }

            return((int)res);
        }
Beispiel #16
0
 private static IntPtr dlopen(string libraryName, int flags)
 {
     byte[] libNameBytes = Encoding.UTF8.GetBytes(libraryName);
     fixed(byte *pName = libNameBytes)
     {
         return(new IntPtr(LibC.dlopen(pName, flags)));
     }
 }
Beispiel #17
0
 public override TimeSpan getCurrentTime()
 {
     if (presentationStart.HasValue)
     {
         TimeSpan now = LibC.gettime(eClock.Monotonic);
         return(now - presentationStart.Value);
     }
     return(TimeSpan.Zero);
 }
Beispiel #18
0
        public static void Main(string[] args)
        {
            // Workaround for mono issue #12557: https://github.com/mono/mono/issues/12557
            Environment.SetEnvironmentVariable("MONO_MANAGED_WATCHER", "dummy");

            var code = Arc.YTSubConverter.Program.Main(args);

            LibC.exit(code);
        }
Beispiel #19
0
        private unsafe static string GetErrorMessage(int errno)
        {
            int   bufferLength = 1024;
            byte *buffer       = stackalloc byte[bufferLength];

            int rv = LibC.strerror_r(errno, buffer, bufferLength);

            return(rv == 0 ? Marshal.PtrToStringAnsi((IntPtr)buffer) : $"errno {errno}");
        }
Beispiel #20
0
 static void openEndpoint(string path, ref FileHandle file, ref IntPtr mapped, int size)
 {
     file   = FileHandle.openFile(path, eFileFlags.O_RDWR | eFileFlags.O_SYNC);
     mapped = LibC.mmap(IntPtr.Zero, (UIntPtr)size, eMemoryProtection.ReadWrite, (int)eMapFlags.Shared, file, (IntPtr)0);
     if (mapped == LibC.MAP_FAILED)
     {
         throw LibC.exception($"memory map failed for device \"{ path }\"", -1);
     }
 }
Beispiel #21
0
        protected override bool ReleaseHandle()
        {
            var rv = LibC.close(handle.ToInt32());

            if (rv == -1)
            {
                PlatformException.Throw();
            }
            return(true);
        }
 private static IntPtr dlopen(string libraryName, int flags)
 {
     Console.WriteLine($"Open Library: {libraryName} {flags}");
     byte[] libNameBytes = Encoding.UTF8.GetBytes(libraryName);
     fixed(byte *pName = libNameBytes)
     {
         Console.WriteLine($"Found dlopen: {LibraryName} {flags}");
         return(new IntPtr(LibC.dlopen(pName, flags)));
     }
 }
Beispiel #23
0
        public static int Open(IVfsPath path, int flags, mode_t mode = default)
        {
            var fd = LibC.open(path.toNullTerm(), 0);

            if (LibC.errno != 0)
            {
                return(-LibC.errno);
            }
            return(fd);
        }
Beispiel #24
0
        /// <nodoc />
        public static void OverrideFileAccessMode(bool changePermissions, string path)
        {
#if !PLATFORM_WIN
            if (changePermissions)
            {
                // Force 0777 on the file at 'path' - this is a temporary hack when placing files as our cache layer
                // currently does not track Unix file access flags when putting / placing files
                LibC.chmod(path, LibC.AllFilePermssionMask);
            }
#endif
        }
Beispiel #25
0
 private static FileInfo ToFileInfo(stat stat)
 {
     return(new FileInfo
     {
         Mode = Convert.ToInt32(stat.st_mode.ToString()),
         IsLink = LibC.S_ISLNK(stat.st_mode),
         OwnerId = Convert.ToInt32(stat.st_uid.ToString()),
         GroupId = Convert.ToInt32(stat.st_gid.ToString()),
         LastModTime = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(stat.st_mtim.tv_sec.ToString())).UtcDateTime,
     });
 }
Beispiel #26
0
 private static IntPtr dlvsym(IntPtr libHandle, string name, string version)
 {
     byte[] functionName = Encoding.UTF8.GetBytes(name);
     fixed(byte *pName = functionName)
     {
         fixed(byte *pVersion = Encoding.UTF8.GetBytes(version))
         {
             return(new IntPtr(LibC.dlvsym(libHandle.ToPointer(), pName, pVersion)));
         }
     }
 }
Beispiel #27
0
        static void MaxOpenFiles(bool change)
        {
            var lim = new LibC.rlimit();
            var ok  = LibC.getrlimit((int)LibC.RLimit.NoFile, ref lim);

            Console.WriteLine($"getrlimit({lim.cur}, {lim.max}) => {ok}");

            if (!change)
            {
                return;
            }

            int n = 9000;

            lim.cur = lim.max = (UInt64)n;
            ok      = LibC.setrlimit((int)LibC.RLimit.NoFile, ref lim);
            Console.WriteLine($"setrlimit({lim.cur}, {lim.max}) => {ok}");
            ok = LibC.getrlimit((int)LibC.RLimit.NoFile, ref lim);
            Console.WriteLine($"getrlimit({lim.cur}, {lim.max}) => {ok}");

            lim.cur = (UInt64)4000;
            ok      = LibC.setrlimit((int)LibC.RLimit.NoFile, ref lim);
            Console.WriteLine($"setrlimit({lim.cur}, {lim.max}) => {ok}");
            ok = LibC.getrlimit((int)LibC.RLimit.NoFile, ref lim);
            Console.WriteLine($"getrlimit({lim.cur}, {lim.max}) => {ok}");

            var a = new Stream[n];
            var f = Path.GetTempFileName();
            int i = 0;

            try
            {
                for (i = 0; i < n; ++i)
                {
                    a[i] = new FileStream(f, FileMode.Open, FileAccess.Read);
                    //var result = LibC.open(f, LibC.FileMode.S_IRUSR);
                    //var result = LibC.fopen(f, "rb");
                    //if (result == IntPtr.Zero)
                    //break;
                }
            }
            catch
            {
            }
            finally
            {
                for (int j = i - 1; j >= 0; --j)
                {
                    
 a[j].Close();
                }
                

            }
            Console.WriteLine($"#{i}");
        }
        private void CallIsatty()
        {
            int current_status = LibC.isatty((char)fd.Value);

            status.Value = (uint)current_status;
            if (current_status == 0)
            {
                SetErrorNumber();
            }
            call = Call.Done;
        }
        private void CallClose()
        {
            int current_status = LibC.close((int)fd.Value);

            status.Value = (uint)current_status;
            if (current_status == -1)
            {
                SetErrorNumber();
            }
            call = Call.Done;
        }
        private void CallLseek()
        {
            int current_status = LibC.lseek((int)fd.Value, Convert.ToInt64((int)offset.Value), (int)origin.Value);

            position.Value = (uint)current_status;
            if (current_status == -1)
            {
                SetErrorNumber();
            }
            call = Call.Done;
        }