private static SafeMemoryMappedFileHandle CreateCore(
            FileStream fileStream, string mapName, HandleInheritability inheritability,
            MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity)
        {
            SafeFileHandle fileHandle = fileStream != null ? fileStream.SafeFileHandle : null;
            Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability);


            SafeMemoryMappedFileHandle handle = fileHandle != null ?
                Interop.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName) :
                Interop.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName);

            int errorCode = Marshal.GetLastWin32Error();
            if (!handle.IsInvalid)
            {
                if (errorCode == Interop.Errors.ERROR_ALREADY_EXISTS)
                {
                    handle.Dispose();
                    throw Win32Marshal.GetExceptionForWin32Error(errorCode);
                }
            }
            else // handle.IsInvalid
            {
                handle.Dispose();
                throw Win32Marshal.GetExceptionForWin32Error(errorCode);
            }

            return handle;
        }
        public void OpenCreatedNew(string mapName, MemoryMappedFileRights desiredAccessRights, HandleInheritability inheritability)
        {
            const int Capacity = 4096;
            using (MemoryMappedFile original = MemoryMappedFile.CreateNew(mapName, Capacity))
            {
                using (MemoryMappedFile opened = MemoryMappedFile.OpenExisting(mapName))
                {
                    Assert.Throws<IOException>(() => MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.AccessSystemSecurity));
                    Assert.Throws<IOException>(() => MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.AccessSystemSecurity, HandleInheritability.None));
                    ValidateMemoryMappedFile(opened, Capacity);
                }
                using (MemoryMappedFile opened = MemoryMappedFile.OpenExisting(mapName, desiredAccessRights | MemoryMappedFileRights.ReadPermissions)) // can't do anything if we don't have read permissions
                {
                    ValidateMemoryMappedFile(opened, Capacity, RightsToAccess(desiredAccessRights));
                }
                using (MemoryMappedFile opened = MemoryMappedFile.OpenExisting(mapName, desiredAccessRights | MemoryMappedFileRights.ReadPermissions, inheritability))
                {
                    ValidateMemoryMappedFile(opened, Capacity, RightsToAccess(desiredAccessRights), inheritability);
                }
            }

            // The map no longer exists
            Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.OpenExisting(mapName));
            Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.ReadWrite));
            Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.ReadWrite, HandleInheritability.None));
        }
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                HandleInheritability inheritability)
        {
            Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty");
            Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
            Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
            Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
            Debug.Assert((maxNumberOfServerInstances >= 1) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");

            if (transmissionMode == PipeTransmissionMode.Message)
            {
                throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode);
            }

            // NOTE: We don't have a good way to enforce maxNumberOfServerInstances, and don't currently try.
            // It's a Windows-specific concept.

            _path = GetPipePath(".", pipeName);
            _direction = direction;
            _options = options;
            _inBufferSize = inBufferSize;
            _outBufferSize = outBufferSize;
            _inheritability = inheritability;
        }
        private NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                HandleInheritability inheritability)
            : base(direction, transmissionMode, outBufferSize)
        {
            if (pipeName == null)
            {
                throw new ArgumentNullException("pipeName");
            }
            if (pipeName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_NeedNonemptyPipeName);
            }
            if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0)
            {
                throw new ArgumentOutOfRangeException("options", SR.ArgumentOutOfRange_OptionsInvalid);
            }
            if (inBufferSize < 0)
            {
                throw new ArgumentOutOfRangeException("inBufferSize", SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            ValidateMaxNumberOfServerInstances(maxNumberOfServerInstances);
            // inheritability will always be None since this private constructor is only called from other constructors from which
            // inheritability is always set to None. Desktop has a public constructor to allow setting it to something else, but Core
            // doesnt.
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException("inheritability", SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
            }

            Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode,
                options, inBufferSize, outBufferSize, inheritability);
        }
Example #5
0
        public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRights desiredAccessRights,
                                                                    HandleInheritability inheritability)
        {
            if (mapName == null)
            {
                throw new ArgumentNullException("mapName", SR.ArgumentNull_MapName);
            }

            if (mapName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_MapNameEmptyString);
            }

            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException("inheritability");
            }

            if (((int)desiredAccessRights & ~((int)(MemoryMappedFileRights.FullControl | MemoryMappedFileRights.AccessSystemSecurity))) != 0)
            {
                throw new ArgumentOutOfRangeException("desiredAccessRights");
            }

            SafeMemoryMappedFileHandle handle = OpenCore(mapName, inheritability, desiredAccessRights, false);
            return new MemoryMappedFile(handle);
        }
        private NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                HandleInheritability inheritability)
            : base(direction, transmissionMode, outBufferSize)
        {
            if (pipeName == null)
            {
                throw new ArgumentNullException("pipeName");
            }
            if (pipeName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_NeedNonemptyPipeName);
            }
            if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0)
            {
                throw new ArgumentOutOfRangeException("options", SR.ArgumentOutOfRange_OptionsInvalid);
            }
            if (inBufferSize < 0)
            {
                throw new ArgumentOutOfRangeException("inBufferSize", SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            // win32 allows fixed values of 1-254 or 255 to mean max allowed by system. We expose 255 as -1 (unlimited)
            // through the MaxAllowedServerInstances constant. This is consistent e.g. with -1 as infinite timeout, etc
            if ((maxNumberOfServerInstances < 1 || maxNumberOfServerInstances > 254) && (maxNumberOfServerInstances != MaxAllowedServerInstances))
            {
                throw new ArgumentOutOfRangeException("maxNumberOfServerInstances", SR.ArgumentOutOfRange_MaxNumServerInstances);
            }
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException("inheritability", SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
            }

            Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode,
                options, inBufferSize, outBufferSize, inheritability);
        }
        private static unsafe SafeMemoryMappedFileHandle CreateCore(
            FileStream fileStream, string mapName, 
            HandleInheritability inheritability, MemoryMappedFileAccess access, 
            MemoryMappedFileOptions options, long capacity)
        {
            if (mapName != null)
            {
                // Named maps are not supported in our Unix implementation.  We could support named maps on Linux using 
                // shared memory segments (shmget/shmat/shmdt/shmctl/etc.), but that doesn't work on OSX by default due
                // to very low default limits on OSX for the size of such objects; it also doesn't support behaviors
                // like copy-on-write or the ability to control handle inheritability, and reliably cleaning them up
                // relies on some non-conforming behaviors around shared memory IDs remaining valid even after they've
                // been marked for deletion (IPC_RMID).  We could also support named maps using the current implementation
                // by not unlinking after creating the backing store, but then the backing stores would remain around
                // and accessible even after process exit, with no good way to appropriately clean them up.
                // (File-backed maps may still be used for cross-process communication.)
                throw CreateNamedMapsNotSupportedException();
            }

            bool ownsFileStream = false;
            if (fileStream != null)
            {
                // This map is backed by a file.  Make sure the file's size is increased to be
                // at least as big as the requested capacity of the map.
                if (fileStream.Length < capacity)
                {
                    try
                    {
                        fileStream.SetLength(capacity);
                    }
                    catch (ArgumentException exc)
                    {
                        // If the capacity is too large, we'll get an ArgumentException from SetLength, 
                        // but on Windows this same condition is represented by an IOException.
                        throw new IOException(exc.Message, exc);
                    }
                }
            }
            else
            {
                // This map is backed by memory-only.  With files, multiple views over the same map
                // will end up being able to share data through the same file-based backing store;
                // for anonymous maps, we need a similar backing store, or else multiple views would logically 
                // each be their own map and wouldn't share any data.  To achieve this, we create a backing object
                // (either memory or on disk, depending on the system) and use its file descriptor as the file handle.  
                // However, we only do this when the permission is more than read-only.  We can't change the size 
                // of an object that has read-only permissions, but we also don't need to worry about sharing
                // views over a read-only, anonymous, memory-backed map, because the data will never change, so all views
                // will always see zero and can't change that.  In that case, we just use the built-in anonymous support of
                // the map by leaving fileStream as null.
                Interop.libc.MemoryMappedProtections protections = MemoryMappedView.GetProtections(access, forVerification: false);
                if ((protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0 && capacity > 0)
                {
                    ownsFileStream = true;
                    fileStream = CreateSharedBackingObject(protections, capacity);
                }
            }

            return new SafeMemoryMappedFileHandle(fileStream, ownsFileStream, inheritability, access, options, capacity);
        }
        /// <summary>Performs basic verification on a map.</summary>
        /// <param name="mmf">The map.</param>
        /// <param name="expectedCapacity">The capacity that was specified to create the map.</param>
        /// <param name="expectedAccess">The access specified to create the map.</param>
        /// <param name="expectedInheritability">The inheritability specified to create the map.</param>
        protected static void ValidateMemoryMappedFile(MemoryMappedFile mmf, 
            long expectedCapacity, 
            MemoryMappedFileAccess expectedAccess = MemoryMappedFileAccess.ReadWrite,
            HandleInheritability expectedInheritability = HandleInheritability.None)
        {
            // Validate that we got a MemoryMappedFile object and that its handle is valid
            Assert.NotNull(mmf);
            Assert.NotNull(mmf.SafeMemoryMappedFileHandle);
            Assert.Same(mmf.SafeMemoryMappedFileHandle, mmf.SafeMemoryMappedFileHandle);
            Assert.False(mmf.SafeMemoryMappedFileHandle.IsClosed);
            Assert.False(mmf.SafeMemoryMappedFileHandle.IsInvalid);
            AssertInheritability(mmf.SafeMemoryMappedFileHandle, expectedInheritability);

            // Create and validate one or more views from the map
            if (IsReadable(expectedAccess) && IsWritable(expectedAccess))
            {
                CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.Read);
                CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.Write);
                CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.ReadWrite);
            }
            else if (IsWritable(expectedAccess))
            {
                CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.Write);
            }
            else if (IsReadable(expectedAccess))
            {
                CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.Read);
            }
            else
            {
                Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, expectedCapacity, MemoryMappedFileAccess.Read));
                Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, expectedCapacity, MemoryMappedFileAccess.Write));
                Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, expectedCapacity, MemoryMappedFileAccess.ReadWrite));
            }
        }
        private static SafeMemoryMappedFileHandle CreateCore(
            SafeFileHandle fileHandle, string mapName, HandleInheritability inheritability,
            MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity)
        {
            Interop.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability);

            // split the long into two ints
            int capacityLow = unchecked((int)(capacity & 0x00000000FFFFFFFFL));
            int capacityHigh = unchecked((int)(capacity >> 32));

            SafeMemoryMappedFileHandle handle = fileHandle != null ?
                Interop.mincore.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName) :
                Interop.mincore.CreateFileMapping(Interop.INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName);

            int errorCode = Marshal.GetLastWin32Error();
            if (!handle.IsInvalid)
            {
                if (errorCode == Interop.ERROR_ALREADY_EXISTS)
                {
                    handle.Dispose();
                    throw Win32Marshal.GetExceptionForWin32Error(errorCode);
                }
            }
            else if (handle.IsInvalid)
            {
                throw Win32Marshal.GetExceptionForWin32Error(errorCode);
            }

            return handle;
        }
        private void Create(PipeDirection direction, HandleInheritability inheritability, int bufferSize)
        {
            Debug.Assert(direction != PipeDirection.InOut, "Anonymous pipe direction shouldn't be InOut");
            // Ignore bufferSize.  It's optional, and the fcntl F_SETPIPE_SZ for changing it is Linux specific.

            // Use pipe or pipe2 to create our anonymous pipe
            int[] fds = new int[2];
            unsafe
            {
                fixed (int* fdsptr = fds)
                {
                    CreatePipe(inheritability, fdsptr);
                }
            }

            // Create SafePipeHandles for each end of the pipe.  Which ends goes with server and which goes with
            // client depends on the direction of the pipe.
            SafePipeHandle serverHandle = new SafePipeHandle(
                (IntPtr)fds[direction == PipeDirection.In ? Interop.libc.ReadEndOfPipe : Interop.libc.WriteEndOfPipe], 
                ownsHandle: true);
            SafePipeHandle clientHandle = new SafePipeHandle(
                (IntPtr)fds[direction == PipeDirection.In ? Interop.libc.WriteEndOfPipe : Interop.libc.ReadEndOfPipe], 
                ownsHandle: true);

            // We're connected.  Finish initialization using the newly created handles.
            InitializeHandle(serverHandle, isExposed: false, isAsync: false);
            _clientHandle = clientHandle;
            State = PipeState.Connected;
        }
        private void Create(PipeDirection direction, HandleInheritability inheritability, int bufferSize)
        {
            Debug.Assert(direction != PipeDirection.InOut, "Anonymous pipe direction shouldn't be InOut");
            Debug.Assert(bufferSize >= 0, "bufferSize is negative");

            throw NotImplemented.ByDesign; // TODO: Implement this
        }
Example #12
0
 public IMemoryMappedFile OpenExisting(
     string mapName,
     MemoryMappedFileRights desiredAccessRights,
     HandleInheritability inheritability)
 {
     return new MemoryMappedFileWrapper(
         MemoryMappedFile.OpenExisting(mapName, desiredAccessRights, inheritability));
 }
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                HandleInheritability inheritability)
        {
            Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty");
            Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
            Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
            Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
            Debug.Assert((maxNumberOfServerInstances >= 1) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");

            if (transmissionMode == PipeTransmissionMode.Message)
            {
                throw new PlatformNotSupportedException();
            }

            // NOTE: We don't have a good way to enforce maxNumberOfServerInstances, and don't currently try.
            // It's a Windows-specific concept.

            // Make sure the FIFO exists, but don't open it until WaitForConnection is called.
            _path = GetPipePath(".", pipeName);
            while (true)
            {
                int result = Interop.libc.mkfifo(_path, (int)Interop.libc.Permissions.S_IRWXU);
                if (result == 0)
                {
                    // The FIFO was successfully created - note that although we create the FIFO here, we don't
                    // ever delete it. If we remove the FIFO we could invalidate other servers that also use it. 
                    // See #2764 for further discussion.
                    break;
                }

                Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
                if (errorInfo.Error == Interop.Error.EINTR)
                {
                    // interrupted; try again
                    continue;
                }
                else if (errorInfo.Error == Interop.Error.EEXIST)
                {
                    // FIFO already exists; nothing more to do
                    break;
                }
                else
                {
                    // something else; fail
                    throw Interop.GetExceptionForIoErrno(errorInfo, _path);
                }
            }

            // Store the rest of the creation arguments.  They'll be used when we open the connection
            // in WaitForConnection.
            _direction = direction;
            _options = options;
            _inBufferSize = inBufferSize;
            _outBufferSize = outBufferSize;
            _inheritability = inheritability;
        }
 private static SafeMemoryMappedFileHandle CreateOrOpenCore(
     string mapName, 
     HandleInheritability inheritability, MemoryMappedFileAccess access,
     MemoryMappedFileOptions options, long capacity)
 {
     // Since we don't support mapName != null, CreateOrOpenCore can't
     // be used to Open an existing map, and thus is identical to CreateCore.
     return CreateCore(null, mapName, inheritability, access, options, capacity);
 }
Example #15
0
 public IMemoryMappedFile CreateOrOpen(
     string mapName,
     long capacity,
     MemoryMappedFileAccess access,
     MemoryMappedFileOptions options,
     MemoryMappedFileSecurity memoryMappedFileSecurity,
     HandleInheritability inheritability)
 {
     return new MemoryMappedFileWrapper(MemoryMappedFile.CreateOrOpen(
         mapName, capacity, access, options, memoryMappedFileSecurity, inheritability));
 }
Example #16
0
        public AnonymousPipeServerStream(PipeDirection direction, HandleInheritability inheritability, int bufferSize)
            : base(direction, bufferSize) {
            if (direction == PipeDirection.InOut) {
                throw new NotSupportedException(SR.GetString(SR.NotSupported_AnonymousPipeUnidirectional));
            }
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
                throw new ArgumentOutOfRangeException("inheritability", SR.GetString(SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable));
            }

            UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability);
            Create(direction, secAttrs, bufferSize);
        }
        private static unsafe SafeMemoryMappedFileHandle CreateCore(
            SafeFileHandle fileHandle, string mapName, 
            HandleInheritability inheritability, MemoryMappedFileAccess access, 
            MemoryMappedFileOptions options, long capacity)
        {
            if (mapName != null)
            {
                throw CreateNamedMapsNotSupportedException();
            }

            return new SafeMemoryMappedFileHandle(fileHandle, inheritability, access, options, capacity);
        }
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                HandleInheritability inheritability)
        {
            Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty");
            Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
            Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
            Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
            Debug.Assert((maxNumberOfServerInstances >= 1 && maxNumberOfServerInstances <= 254) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");

            throw NotImplemented.ByDesign; // TODO: Implement this
        }
        public AnonymousPipeServerStream(PipeDirection direction, HandleInheritability inheritability, int bufferSize)
            : base(direction, bufferSize)
        {
            if (direction == PipeDirection.InOut)
            {
                throw new NotSupportedException(SR.NotSupported_AnonymousPipeUnidirectional);
            }
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException("inheritability", SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
            }

            Create(direction, inheritability, bufferSize);
        }
		public AnonymousPipeServerStream (PipeDirection direction, HandleInheritability inheritability, int bufferSize, PipeSecurity pipeSecurity)
			: base (direction, bufferSize)
		{
			if (direction == PipeDirection.InOut)
				throw new NotSupportedException ("Anonymous pipe direction can only be either in or out.");

			if (IsWindows)
				impl = new Win32AnonymousPipeServer (this, direction, inheritability, bufferSize, pipeSecurity);
			else
				impl = new UnixAnonymousPipeServer (this, direction, inheritability, bufferSize);

			InitializeHandle (impl.Handle, false, false);
			IsConnected = true;
		}
Example #21
0
		public NamedPipeServerStream (string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights)
			: base (direction, transmissionMode, outBufferSize)
		{
			if (pipeSecurity != null)
				throw ThrowACLException ();
			var rights = ToAccessRights (direction) | additionalAccessRights;
			// FIXME: reject some rights declarations (for ACL).

			if (IsWindows)
				impl = new Win32NamedPipeServer (this, pipeName, maxNumberOfServerInstances, transmissionMode, rights, options, inBufferSize, outBufferSize, inheritability);
			else
				impl = new UnixNamedPipeServer (this, pipeName, maxNumberOfServerInstances, transmissionMode, rights, options, inBufferSize, outBufferSize, inheritability);

			InitializeHandle (impl.Handle, false, (options & PipeOptions.Asynchronous) != PipeOptions.None);
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="OverlappingPipeClientStream"/> class.
 /// </summary>
 /// <param name="serverName">Name of the server.</param>
 /// <param name="pipeName">Name of the pipe.</param>
 /// <param name="transmissionMode"></param>
 /// <param name="impersonationLevel">The impersonation level.</param>
 /// <param name="inheritability">The inheritability.</param>
 public OverlappingPipeClientStream(
     [NotNull] string serverName,
     [NotNull] string pipeName,
     PipeTransmissionMode transmissionMode,
     TokenImpersonationLevel impersonationLevel = TokenImpersonationLevel.None,
     HandleInheritability inheritability = HandleInheritability.None)
     : base(new NamedPipeClientStream(
                serverName,
                pipeName,
                PipeDirection.InOut,
                PipeOptions.Asynchronous,
                impersonationLevel,
                inheritability))
 {
     Debug.Assert(Stream != null);
     ReadMode = transmissionMode;
 }
        /// <summary>Initializes the memory-mapped file handle.</summary>
        /// <param name="fileHandle">The underlying file handle; this may be null in the case of a page-file backed memory-mapped file.</param>
        /// <param name="inheritability">The inheritability of the memory-mapped file.</param>
        /// <param name="access">The access for the memory-mapped file.</param>
        /// <param name="options">The options for the memory-mapped file.</param>
        /// <param name="capacity">The capacity of the memory-mapped file.</param>
        internal SafeMemoryMappedFileHandle(
            SafeFileHandle fileHandle, HandleInheritability inheritability,
            MemoryMappedFileAccess access, MemoryMappedFileOptions options,
            long capacity)
            : base(new IntPtr(-1), ownsHandle: true)
        {
            // Store the arguments.  We'll actually open the map when the view is created.
            _fileHandle = fileHandle;
            _inheritability = inheritability;
            _access = access;
            _options = options;
            _capacity = capacity;

            // Fake a unique int handle value > 0.
            int nextHandleValue = (int)((Interlocked.Increment(ref s_counter) % (int.MaxValue - 1)) + 1);
            SetHandle(new IntPtr(nextHandleValue));
        }
        private static unsafe SafeMemoryMappedFileHandle CreateCore(
            FileStream fileStream, string mapName, 
            HandleInheritability inheritability, MemoryMappedFileAccess access, 
            MemoryMappedFileOptions options, long capacity)
        {
            if (mapName != null)
            {
                // TODO: We currently do not support named maps.  We could possibly support 
                // named maps in the future by using shm_open / shm_unlink, as we do for
                // giving internal names to anonymous maps.  Issues to work through will include 
                // dealing with permissions, passing information from the creator of the 
                // map to another opener of it, etc.
                throw CreateNamedMapsNotSupportedException();
            }

            var fileStreamSource = SafeMemoryMappedFileHandle.FileStreamSource.Provided;
            if (fileStream != null)
            {
                // This map is backed by a file.  Make sure the file's size is increased to be
                // at least as big as the requested capacity of the map.
                if (fileStream.Length < capacity)
                {
                    fileStream.SetLength(capacity);
                }
            }
            else
            {
                // This map is backed by memory-only.  With files, multiple views over the same map
                // will end up being able to share data through the same file-based backing store;
                // for anonymous maps, we need a similar backing store, or else multiple views would logically 
                // each be their own map and wouldn't share any data.  To achieve this, we create a backing object
                // (either memory or on disk, depending on the system) and use its file descriptor as the file handle.  
                // However, we only do this when the permission is more than read-only.  We can't change the size 
                // of an object that has read-only permissions, but we also don't need to worry about sharing
                // views over a read-only, anonymous, memory-backed map, because the data will never change, so all views
                // will always see zero and can't change that.  In that case, we just use the built-in anonymous support of
                // the map by leaving fileHandle as null.
                Interop.libc.MemoryMappedProtections protections = MemoryMappedView.GetProtections(access, forVerification: false);
                if ((protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0 && capacity > 0)
                {
                    fileStream = CreateSharedBackingObject(protections, capacity, out mapName, out fileStreamSource);
                }
            }

            return new SafeMemoryMappedFileHandle(mapName, fileStream, fileStreamSource, inheritability, access, options, capacity);
        }
Example #25
0
 public IMemoryMappedFile CreateFromFile(
     FileStream fileStream,
     string mapName,
     long capacity,
     MemoryMappedFileAccess access,
     MemoryMappedFileSecurity memoryMappedFileSecurity,
     HandleInheritability inheritability,
     bool leaveOpen)
 {
     return new MemoryMappedFileWrapper(MemoryMappedFile.CreateFromFile(
         fileStream,
         mapName,
         capacity,
         access,
         memoryMappedFileSecurity,
         inheritability,
         leaveOpen));
 }
Example #26
0
		// AnonymousPipeServerStream owner;

		public Win32AnonymousPipeServer (AnonymousPipeServerStream owner, PipeDirection direction, HandleInheritability inheritability, int bufferSize)
		{
			IntPtr r, w;
			SecurityAttributesHack att = new SecurityAttributesHack (inheritability == HandleInheritability.Inheritable);
			if (!Win32Marshal.CreatePipe (out r, out w, ref att, bufferSize))
				throw new Win32Exception (Marshal.GetLastWin32Error ());

			var rh = new SafePipeHandle (r, true);
			var wh = new SafePipeHandle (w, true);

			if (direction == PipeDirection.Out) {
				server_handle = wh;
				client_handle = rh;
			} else {
				server_handle = rh;
				client_handle = wh;
			}
		}
 public NamedPipeClientStream(string serverName, string pipeName, PipeAccessRights desiredAccessRights, PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability) : base(DirectionFromRights(desiredAccessRights), 0)
 {
     if (pipeName == null)
     {
         throw new ArgumentNullException("pipeName");
     }
     if (serverName == null)
     {
         throw new ArgumentNullException("serverName", System.SR.GetString("ArgumentNull_ServerName"));
     }
     if (pipeName.Length == 0)
     {
         throw new ArgumentException(System.SR.GetString("Argument_NeedNonemptyPipeName"));
     }
     if (serverName.Length == 0)
     {
         throw new ArgumentException(System.SR.GetString("Argument_EmptyServerName"));
     }
     if ((options & ~(PipeOptions.Asynchronous | PipeOptions.WriteThrough)) != PipeOptions.None)
     {
         throw new ArgumentOutOfRangeException("options", System.SR.GetString("ArgumentOutOfRange_OptionsInvalid"));
     }
     if ((impersonationLevel < TokenImpersonationLevel.None) || (impersonationLevel > TokenImpersonationLevel.Delegation))
     {
         throw new ArgumentOutOfRangeException("impersonationLevel", System.SR.GetString("ArgumentOutOfRange_ImpersonationInvalid"));
     }
     if ((inheritability < HandleInheritability.None) || (inheritability > HandleInheritability.Inheritable))
     {
         throw new ArgumentOutOfRangeException("inheritability", System.SR.GetString("ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable"));
     }
     if ((desiredAccessRights & ~(PipeAccessRights.AccessSystemSecurity | PipeAccessRights.FullControl)) != 0)
     {
         throw new ArgumentOutOfRangeException("desiredAccessRights", System.SR.GetString("ArgumentOutOfRange_InvalidPipeAccessRights"));
     }
     this.m_normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName);
     if (string.Compare(this.m_normalizedPipePath, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase) == 0)
     {
         throw new ArgumentOutOfRangeException("pipeName", System.SR.GetString("ArgumentOutOfRange_AnonymousReserved"));
     }
     this.m_inheritability = inheritability;
     this.m_impersonationLevel = impersonationLevel;
     this.m_pipeOptions = options;
     this.m_access = (int) desiredAccessRights;
 }
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                HandleInheritability inheritability)
        {
            Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty");
            Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
            Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
            Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
            Debug.Assert((maxNumberOfServerInstances >= 1 && maxNumberOfServerInstances <= 254) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");

            string fullPipeName = Path.GetFullPath(@"\\.\pipe\" + pipeName);

            // Make sure the pipe name isn't one of our reserved names for anonymous pipes.
            if (String.Equals(fullPipeName, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentOutOfRangeException("pipeName", SR.ArgumentOutOfRange_AnonymousReserved);
            }


            int openMode = ((int)direction) |
                           (maxNumberOfServerInstances == 1 ? Interop.mincore.FileOperations.FILE_FLAG_FIRST_PIPE_INSTANCE : 0) |
                           (int)options;

            // We automatically set the ReadMode to match the TransmissionMode.
            int pipeModes = (int)transmissionMode << 2 | (int)transmissionMode << 1;

            // Convert -1 to 255 to match win32 (we asserted that it is between -1 and 254).
            if (maxNumberOfServerInstances == MaxAllowedServerInstances)
            {
                maxNumberOfServerInstances = 255;
            }

            Interop.mincore.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability);
            SafePipeHandle handle = Interop.mincore.CreateNamedPipe(fullPipeName, openMode, pipeModes,
                maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, ref secAttrs);

            if (handle.IsInvalid)
            {
                throw Win32Marshal.GetExceptionForLastWin32Error();
            }

            InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0);
        }
        private void Create(PipeDirection direction, HandleInheritability inheritability, int bufferSize)
        {
            Debug.Assert(direction != PipeDirection.InOut, "Anonymous pipe direction shouldn't be InOut");
            Debug.Assert(bufferSize >= 0, "bufferSize is negative");

            bool bSuccess;
            SafePipeHandle serverHandle;
            SafePipeHandle newServerHandle;

            // Create the two pipe handles that make up the anonymous pipe.
            Interop.mincore.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability);
            if (direction == PipeDirection.In)
            {
                bSuccess = Interop.mincore.CreatePipe(out serverHandle, out _clientHandle, ref secAttrs, bufferSize);
            }
            else
            {
                bSuccess = Interop.mincore.CreatePipe(out _clientHandle, out serverHandle, ref secAttrs, bufferSize);
            }

            if (!bSuccess)
            {
                throw Win32Marshal.GetExceptionForLastWin32Error();
            }

            // Duplicate the server handle to make it not inheritable.  Note: We need to do this so that the child 
            // process doesn't end up getting another copy of the server handle.  If it were to get a copy, the
            // OS wouldn't be able to inform the child that the server has closed its handle because it will see
            // that there is still one server handle that is open.  
            bSuccess = Interop.mincore.DuplicateHandle(Interop.mincore.GetCurrentProcess(), serverHandle, Interop.mincore.GetCurrentProcess(),
                out newServerHandle, 0, false, Interop.mincore.HandleOptions.DUPLICATE_SAME_ACCESS);

            if (!bSuccess)
            {
                throw Win32Marshal.GetExceptionForLastWin32Error();
            }

            // Close the inheritable server handle.
            serverHandle.Dispose();

            InitializeHandle(newServerHandle, false, false);

            State = PipeState.Connected;
        }
        /// <summary>Initializes the memory-mapped file handle.</summary>
        /// <param name="fileStream">The underlying file stream; may be null.</param>
        /// <param name="ownsFileStream">Whether this SafeHandle is responsible for Disposing the fileStream.</param>
        /// <param name="inheritability">The inheritability of the memory-mapped file.</param>
        /// <param name="access">The access for the memory-mapped file.</param>
        /// <param name="options">The options for the memory-mapped file.</param>
        /// <param name="capacity">The capacity of the memory-mapped file.</param>
        internal SafeMemoryMappedFileHandle(
            FileStream fileStream, bool ownsFileStream, HandleInheritability inheritability,
            MemoryMappedFileAccess access, MemoryMappedFileOptions options,
            long capacity)
            : base(new IntPtr(-1), ownsHandle: true)
        {
            Debug.Assert(!ownsFileStream || fileStream != null, "We can only own a FileStream we're actually given.");

            // Store the arguments.  We'll actually open the map when the view is created.
            _fileStream = fileStream;
            _ownsFileStream = ownsFileStream;
            _inheritability = inheritability;
            _access = access;
            _options = options;
            _capacity = capacity;

            // Fake a unique int handle value > 0.
            int nextHandleValue = (int)((Interlocked.Increment(ref s_counter) % (int.MaxValue - 1)) + 1);
            SetHandle(new IntPtr(nextHandleValue));
        }
 public void InvalidArguments_Inheritability(HandleInheritability inheritability)
 {
     AssertExtensions.Throws <ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateNew(null, 4096, MemoryMappedFileAccess.Read, MemoryMappedFileOptions.None, inheritability));
 }
Example #32
0
    public void VerifyCreateNewException <EXCTYPE>(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) where EXCTYPE : Exception
    {
        if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows)
        {
            return;
        }

        iCountTestcases++;
        try
        {
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability))
            {
                iCountErrors++;
                Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
            }
        }
        catch (EXCTYPE)
        {
            //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
        }
        catch (Exception ex)
        {
            iCountErrors++;
            Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
        }
    }
Example #33
0
 /// <summary>
 /// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
 /// We'll throw an ArgumentException if the file mapping object didn't exist and the
 /// caller used CreateOrOpen since Create isn't valid with Write access
 /// </summary>
 private static SafeMemoryMappedFileHandle OpenCore(
     string mapName, HandleInheritability inheritability, MemoryMappedFileRights rights, bool createOrOpen)
 {
     throw CreateNamedMapsNotSupportedException();
 }
Example #34
0
        // -----------------------------
        // ---- PAL layer ends here ----
        // -----------------------------

        internal static Interop.libc.OpenFlags TranslateFlags(PipeDirection direction, PipeOptions options, HandleInheritability inheritability)
        {
            // Translate direction
            Interop.libc.OpenFlags flags =
                direction == PipeDirection.InOut ? Interop.libc.OpenFlags.O_RDWR :
                direction == PipeDirection.Out ? Interop.libc.OpenFlags.O_WRONLY :
                Interop.libc.OpenFlags.O_RDONLY;

            // Translate options
            if ((options & PipeOptions.WriteThrough) != 0)
            {
                flags |= Interop.libc.OpenFlags.O_SYNC;
            }

            // Translate inheritability.
            if ((inheritability & HandleInheritability.Inheritable) == 0)
            {
                flags |= Interop.libc.OpenFlags.O_CLOEXEC;
            }

            // PipeOptions.Asynchronous is ignored, at least for now.  Asynchronous processing
            // is handling just by queueing a work item to do the work synchronously on a pool thread.

            return(flags);
        }
Example #35
0
        public void ValidArgumentCombinations_Execute(
            string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability)
        {
            // Map doesn't exist
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access))
            {
                ValidateMemoryMappedFile(mmf, capacity, access);
            }
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability))
            {
                ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
            }

            // Map does exist (CreateNew)
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access))
                using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access))
                {
                    ValidateMemoryMappedFile(mmf2, capacity, access);
                }
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability))
                using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability))
                {
                    ValidateMemoryMappedFile(mmf2, capacity, access, inheritability);
                }

            // (Avoid testing with CreateFromFile when using execute permissions.)
        }
        internal NamedPipeClientStream(String serverName, String pipeName, PipeDirection direction,
                                       PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability)
            : base(direction, 0)
        {
            if (pipeName == null)
            {
                throw new ArgumentNullException("pipeName");
            }
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName", SR.ArgumentNull_ServerName);
            }
            if (pipeName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_NeedNonemptyPipeName);
            }
            if (serverName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_EmptyServerName);
            }
            if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0)
            {
                throw new ArgumentOutOfRangeException("options", SR.ArgumentOutOfRange_OptionsInvalid);
            }
            if (impersonationLevel < TokenImpersonationLevel.None || impersonationLevel > TokenImpersonationLevel.Delegation)
            {
                throw new ArgumentOutOfRangeException("impersonationLevel", SR.ArgumentOutOfRange_ImpersonationInvalid);
            }
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException("inheritability", SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
            }

            _normalizedPipePath = GetPipePath(serverName, pipeName);
            _direction          = direction;
            _inheritability     = inheritability;
            _impersonationLevel = impersonationLevel;
            _pipeOptions        = options;
        }
Example #37
0
 public void Create_ValidParameters(PipeDirection direction, HandleInheritability inheritability, int bufferSize)
 {
     CreateAndVerifyAnonymousPipe(GetBasicPipeSecurity(), direction, inheritability, bufferSize).Dispose();
 }
Example #38
0
 public void VerifyOpen(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability, MemoryMappedFileAccess expectedAccess)
 {
     iCountTestcases++;
     try
     {
         using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability))
         {
             VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, inheritability);
             VerifyAccess(strLoc, mmf, expectedAccess, 10);
         }
     }
     catch (Exception ex)
     {
         iCountErrors++;
         Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
     }
 }
Example #39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PipeClientWithCallback"/> class.
 /// </summary>
 /// <param name="pipeName">The name of the pipe.</param>
 /// <param name="handlerFactoryFunc">A factory function to provide the handler implementation.</param>
 /// <param name="options">One of the enumeration values that determines how to open or create the pipe.</param>
 /// <param name="impersonationLevel">One of the enumeration values that determines the security impersonation level.</param>
 /// <param name="inheritability">One of the enumeration values that determines whether the underlying handle will be inheritable by child processes.</param>
 public PipeClientWithCallback(string pipeName, Func <THandling> handlerFactoryFunc, PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability)
     : this(".", pipeName, handlerFactoryFunc, options, impersonationLevel, inheritability)
 {
 }
Example #40
0
        /// <summary>
        /// Used by the 2 Create factory method groups.  A null fileHandle specifies that the
        /// memory mapped file should not be associated with an existing file on disk (i.e. start
        /// out empty).
        /// </summary>
        private static unsafe SafeMemoryMappedFileHandle CreateCore(
            FileStream?fileStream, string?mapName,
            HandleInheritability inheritability, MemoryMappedFileAccess access,
            MemoryMappedFileOptions options, long capacity)
        {
            VerifyMemoryMappedFileAccess(access, capacity, fileStream, out long fileSize);

            if (mapName != null)
            {
                // Named maps are not supported in our Unix implementation.  We could support named maps on Linux using
                // shared memory segments (shmget/shmat/shmdt/shmctl/etc.), but that doesn't work on OSX by default due
                // to very low default limits on OSX for the size of such objects; it also doesn't support behaviors
                // like copy-on-write or the ability to control handle inheritability, and reliably cleaning them up
                // relies on some non-conforming behaviors around shared memory IDs remaining valid even after they've
                // been marked for deletion (IPC_RMID).  We could also support named maps using the current implementation
                // by not unlinking after creating the backing store, but then the backing stores would remain around
                // and accessible even after process exit, with no good way to appropriately clean them up.
                // (File-backed maps may still be used for cross-process communication.)
                throw CreateNamedMapsNotSupportedException();
            }

            bool ownsFileStream = false;

            if (fileStream != null)
            {
                if (fileSize >= 0 && capacity > fileSize)
                {
                    // This map is backed by a file.  Make sure the file's size is increased to be
                    // at least as big as the requested capacity of the map for Write* access.
                    try
                    {
                        fileStream.SetLength(capacity);
                    }
                    catch (ArgumentException exc)
                    {
                        // If the capacity is too large, we'll get an ArgumentException from SetLength,
                        // but on Windows this same condition is represented by an IOException.
                        throw new IOException(exc.Message, exc);
                    }
                }
            }
            else
            {
                // This map is backed by memory-only.  With files, multiple views over the same map
                // will end up being able to share data through the same file-based backing store;
                // for anonymous maps, we need a similar backing store, or else multiple views would logically
                // each be their own map and wouldn't share any data.  To achieve this, we create a backing object
                // (either memory or on disk, depending on the system) and use its file descriptor as the file handle.
                // However, we only do this when the permission is more than read-only.  We can't change the size
                // of an object that has read-only permissions, but we also don't need to worry about sharing
                // views over a read-only, anonymous, memory-backed map, because the data will never change, so all views
                // will always see zero and can't change that.  In that case, we just use the built-in anonymous support of
                // the map by leaving fileStream as null.
                Interop.Sys.MemoryMappedProtections protections = MemoryMappedView.GetProtections(access, forVerification: false);
                if ((protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 && capacity > 0)
                {
                    ownsFileStream = true;
                    fileStream     = CreateSharedBackingObject(protections, capacity, inheritability);
                }
            }

            return(new SafeMemoryMappedFileHandle(fileStream, ownsFileStream, inheritability, access, options, capacity));
        }
        // This overload is used in Mono to implement public constructors.
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                            PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                            PipeSecurity pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights)
        {
            Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty");
            Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
            Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
            Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
            Debug.Assert((maxNumberOfServerInstances >= 1 && maxNumberOfServerInstances <= 254) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");

            string fullPipeName = Path.GetFullPath(@"\\.\pipe\" + pipeName);

            // Make sure the pipe name isn't one of our reserved names for anonymous pipes.
            if (string.Equals(fullPipeName, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
            }

            if (IsCurrentUserOnly)
            {
                Debug.Assert(pipeSecurity == null);

                using (WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent())
                {
                    SecurityIdentifier identifier = currentIdentity.Owner;

                    // Grant full control to the owner so multiple servers can be opened.
                    // Full control is the default per MSDN docs for CreateNamedPipe.
                    PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.FullControl, AccessControlType.Allow);
                    pipeSecurity = new PipeSecurity();

                    pipeSecurity.AddAccessRule(rule);
                    pipeSecurity.SetOwner(identifier);
                }

                // PipeOptions.CurrentUserOnly is special since it doesn't match directly to a corresponding Win32 valid flag.
                // Remove it, while keeping others untouched since historically this has been used as a way to pass flags to CreateNamedPipe
                // that were not defined in the enumeration.
                options &= ~PipeOptions.CurrentUserOnly;
            }

            int openMode = ((int)direction) |
                           (maxNumberOfServerInstances == 1 ? Interop.Kernel32.FileOperations.FILE_FLAG_FIRST_PIPE_INSTANCE : 0) |
                           (int)options |
                           (int)additionalAccessRights;

            // We automatically set the ReadMode to match the TransmissionMode.
            int pipeModes = (int)transmissionMode << 2 | (int)transmissionMode << 1;

            // Convert -1 to 255 to match win32 (we asserted that it is between -1 and 254).
            if (maxNumberOfServerInstances == MaxAllowedServerInstances)
            {
                maxNumberOfServerInstances = 255;
            }

            var pinningHandle = new GCHandle();

            try
            {
                Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability, pipeSecurity, ref pinningHandle);
                SafePipeHandle handle = Interop.Kernel32.CreateNamedPipe(fullPipeName, openMode, pipeModes,
                                                                         maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, ref secAttrs);

                if (handle.IsInvalid)
                {
                    throw Win32Marshal.GetExceptionForLastWin32Error();
                }

                InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0);
            }
            finally
            {
                if (pinningHandle.IsAllocated)
                {
                    pinningHandle.Free();
                }
            }
        }
Example #42
0
        private static FileStream CreateSharedBackingObjectUsingFile(Interop.Sys.MemoryMappedProtections protections, long capacity, HandleInheritability inheritability)
        {
            // We create a temporary backing file in TMPDIR.  We don't bother putting it into subdirectories as the file exists
            // extremely briefly: it's opened/created and then immediately unlinked.
            string path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));

            FileShare share = inheritability == HandleInheritability.None ?
                              FileShare.ReadWrite :
                              FileShare.ReadWrite | FileShare.Inheritable;

            // Create the backing file, then immediately unlink it so that it'll be cleaned up when no longer in use.
            // Then enlarge it to the requested capacity.
            const int DefaultBufferSize = 0x1000;
            var       fs = new FileStream(path, FileMode.CreateNew, TranslateProtectionsToFileAccess(protections), share, DefaultBufferSize);

            try
            {
                Interop.CheckIo(Interop.Sys.Unlink(path));
                fs.SetLength(capacity);
            }
            catch
            {
                fs.Dispose();
                throw;
            }
            return(fs);
        }
Example #43
0
        // -----------------------------
        // ---- PAL layer ends here ----
        // -----------------------------

        private static FileStream?CreateSharedBackingObjectUsingMemory(
            Interop.Sys.MemoryMappedProtections protections, long capacity, HandleInheritability inheritability)
        {
            // The POSIX shared memory object name must begin with '/'.  After that we just want something short and unique.
            string mapName = "/corefx_map_" + Guid.NewGuid().ToString("N");

            // Determine the flags to use when creating the shared memory object
            Interop.Sys.OpenFlags flags = (protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 ?
                                          Interop.Sys.OpenFlags.O_RDWR :
                                          Interop.Sys.OpenFlags.O_RDONLY;
            flags |= Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL; // CreateNew

            // Determine the permissions with which to create the file
            Interop.Sys.Permissions perms = default(Interop.Sys.Permissions);
            if ((protections & Interop.Sys.MemoryMappedProtections.PROT_READ) != 0)
            {
                perms |= Interop.Sys.Permissions.S_IRUSR;
            }
            if ((protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0)
            {
                perms |= Interop.Sys.Permissions.S_IWUSR;
            }
            if ((protections & Interop.Sys.MemoryMappedProtections.PROT_EXEC) != 0)
            {
                perms |= Interop.Sys.Permissions.S_IXUSR;
            }

            // Create the shared memory object.
            SafeFileHandle fd = Interop.Sys.ShmOpen(mapName, flags, (int)perms);

            if (fd.IsInvalid)
            {
                Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
                if (errorInfo.Error == Interop.Error.ENOTSUP)
                {
                    // If ShmOpen is not supported, fall back to file backing object.
                    // Note that the System.Native shim will force this failure on platforms where
                    // the result of native shm_open does not work well with our subsequent call
                    // to mmap.
                    return(null);
                }

                throw Interop.GetExceptionForIoErrno(errorInfo);
            }

            try
            {
                // Unlink the shared memory object immediately so that it'll go away once all handles
                // to it are closed (as with opened then unlinked files, it'll remain usable via
                // the open handles even though it's unlinked and can't be opened anew via its name).
                Interop.CheckIo(Interop.Sys.ShmUnlink(mapName));

                // Give it the right capacity.  We do this directly with ftruncate rather
                // than via FileStream.SetLength after the FileStream is created because, on some systems,
                // lseek fails on shared memory objects, causing the FileStream to think it's unseekable,
                // causing it to preemptively throw from SetLength.
                Interop.CheckIo(Interop.Sys.FTruncate(fd, capacity));

                // shm_open sets CLOEXEC implicitly.  If the inheritability requested is Inheritable, remove CLOEXEC.
                if (inheritability == HandleInheritability.Inheritable &&
                    Interop.Sys.Fcntl.SetFD(fd, 0) == -1)
                {
                    throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo());
                }

                // Wrap the file descriptor in a stream and return it.
                return(new FileStream(fd, TranslateProtectionsToFileAccess(protections)));
            }
            catch
            {
                fd.Dispose();
                throw;
            }
        }
Example #44
0
 private static FileStream CreateSharedBackingObject(Interop.Sys.MemoryMappedProtections protections, long capacity, HandleInheritability inheritability)
 {
     return(CreateSharedBackingObjectUsingMemory(protections, capacity, inheritability)
            ?? CreateSharedBackingObjectUsingFile(protections, capacity, inheritability));
 }
Example #45
0
        public NamedPipeClientStream(string serverName, string pipeName, PipeDirection direction,
                                     PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability)
            : base(direction, 0)
        {
            ArgumentException.ThrowIfNullOrEmpty(pipeName);
            ArgumentNullException.ThrowIfNull(serverName);
            if (serverName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_EmptyServerName);
            }
            if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly)) != 0)
            {
                throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_OptionsInvalid);
            }
            if (impersonationLevel < TokenImpersonationLevel.None || impersonationLevel > TokenImpersonationLevel.Delegation)
            {
                throw new ArgumentOutOfRangeException(nameof(impersonationLevel), SR.ArgumentOutOfRange_ImpersonationInvalid);
            }
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException(nameof(inheritability), SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
            }
            if ((options & PipeOptions.CurrentUserOnly) != 0)
            {
                IsCurrentUserOnly = true;
            }

            _normalizedPipePath = GetPipePath(serverName, pipeName);
            _direction          = direction;
            _inheritability     = inheritability;
            _impersonationLevel = impersonationLevel;
            _pipeOptions        = options;
        }
Example #46
0
    public void VerifyCreateNew(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability)
    {
        if (mapName != null && Interop.PlatformDetection.OperatingSystem != Interop.OperatingSystem.Windows)
        {
            return;
        }

        iCountTestcases++;
        try
        {
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability))
            {
                VerifyAccess(strLoc, mmf, access, capacity);
                VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, inheritability);
            }
        }
        catch (Exception ex)
        {
            iCountErrors++;
            Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
        }
    }
 /// <summary>Initializes a new instance of the <see cref="AnonymousPipeServerStreamAdapter" /> class with the specified pipe direction and inheritability mode.</summary>
 /// <param name="direction">One of the enumeration values that determines the direction of the pipe.Anonymous pipes can only be in one direction, so <paramref name="direction" /> cannot be set to <see cref="F:System.IO.Pipes.PipeDirection.InOut" />.</param>
 /// <param name="inheritability">One of the enumeration values that determines whether the underlying handle can be inherited by child processes. Must be set to either <see cref="F:System.IO.HandleInheritability.None" /> or <see cref="F:System.IO.HandleInheritability.Inheritable" />. </param>
 /// <exception cref="T:System.ArgumentOutOfRangeException">
 /// <paramref name="inheritability" /> is not set to either <see cref="F:System.IO.HandleInheritability.None" /> or <see cref="F:System.IO.HandleInheritability.Inheritable" />.</exception>
 /// <exception cref="T:System.NotSupportedException">
 /// <paramref name="direction" /> is set to <see cref="F:System.IO.Pipes.PipeDirection.InOut" />.</exception>
 public AnonymousPipeServerStreamAdapter(PipeDirection direction, HandleInheritability inheritability)
     : this(new AnonymousPipeServerStream(direction, inheritability))
 {
 }
Example #48
0
 /// <summary>
 /// Used by the OpenExisting factory method group and by CreateOrOpen if access is write.
 /// We'll throw an ArgumentException if the file mapping object didn't exist and the
 /// caller used CreateOrOpen since Create isn't valid with Write access
 /// </summary>
 private static SafeMemoryMappedFileHandle OpenCore(
     string mapName, HandleInheritability inheritability, MemoryMappedFileRights rights, bool createOrOpen)
 {
     return(OpenCore(mapName, inheritability, GetFileMapAccess(rights), createOrOpen));
 }
 private void Create(PipeDirection direction, HandleInheritability inheritability, int bufferSize)
 {
     Create(direction, inheritability, bufferSize, null);
 }
Example #50
0
        /// <summary>
        /// Used by the CreateOrOpen factory method groups.
        /// </summary>
        private static SafeMemoryMappedFileHandle CreateOrOpenCore(
            string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access,
            MemoryMappedFileOptions options, long capacity)
        {
            // Try to open the file if it exists -- this requires a bit more work. Loop until we can
            // either create or open a memory mapped file up to a timeout. CreateFileMapping may fail
            // if the file exists and we have non-null security attributes, in which case we need to
            // use OpenFileMapping.  But, there exists a race condition because the memory mapped file
            // may have closed between the two calls -- hence the loop.
            //
            // The retry/timeout logic increases the wait time each pass through the loop and times
            // out in approximately 1.4 minutes. If after retrying, a MMF handle still hasn't been opened,
            // throw an InvalidOperationException.

            Debug.Assert(access != MemoryMappedFileAccess.Write, "Callers requesting write access shouldn't try to create a mmf");

            SafeMemoryMappedFileHandle?handle = null;

            Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability);

            int waitRetries = 14;   //((2^13)-1)*10ms == approximately 1.4mins
            int waitSleep   = 0;

            // keep looping until we've exhausted retries or break as soon we get valid handle
            while (waitRetries > 0)
            {
                // try to create
                handle = Interop.CreateFileMapping(new IntPtr(-1), ref secAttrs,
                                                   GetPageAccess(access) | (int)options, capacity, mapName);

                if (!handle.IsInvalid)
                {
                    break;
                }
                else
                {
                    handle.Dispose();
                    int createErrorCode = Marshal.GetLastPInvokeError();
                    if (createErrorCode != Interop.Errors.ERROR_ACCESS_DENIED)
                    {
                        throw Win32Marshal.GetExceptionForWin32Error(createErrorCode);
                    }
                }

                // try to open
                handle = Interop.OpenFileMapping(GetFileMapAccess(access), (inheritability &
                                                                            HandleInheritability.Inheritable) != 0, mapName);

                // valid handle
                if (!handle.IsInvalid)
                {
                    break;
                }
                // didn't get valid handle; have to retry
                else
                {
                    handle.Dispose();
                    int openErrorCode = Marshal.GetLastPInvokeError();
                    if (openErrorCode != Interop.Errors.ERROR_FILE_NOT_FOUND)
                    {
                        throw Win32Marshal.GetExceptionForWin32Error(openErrorCode);
                    }

                    // increase wait time
                    --waitRetries;
                    if (waitSleep == 0)
                    {
                        waitSleep = 10;
                    }
                    else
                    {
                        Thread.Sleep(waitSleep);
                        waitSleep *= 2;
                    }
                }
            }

            // finished retrying but couldn't create or open
            if (handle == null || handle.IsInvalid)
            {
                throw new InvalidOperationException(SR.InvalidOperation_CantCreateFileMapping);
            }

            return(handle);
        }
Example #51
0
 internal extern static void ConfigureHandleInheritability(IntPtr handle, HandleInheritability inheritability);
 public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights) : base(default(PipeDirection), default(int))
 {
     Contract.Ensures(1 <= pipeName.Length);
 }
Example #53
0
 public void InvalidArgument_Inheritability(HandleInheritability inheritability)
 {
     Assert.Throws <ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateOrOpen(CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, inheritability));
 }
 public void Create_ValidParameters(PipeOptions options, PipeDirection direction, PipeTransmissionMode transmissionMode, HandleInheritability inheritability, int inBufferSize, int outBufferSize, int maxNumberOfServerInstances, PipeAccessRights rights, AccessControlType controlType)
 {
     if (controlType != AccessControlType.Deny && (rights & ~PipeAccessRights.Synchronize) != 0)
     {
         PipeSecurity security = GetPipeSecurity(WellKnownSidType.BuiltinUsersSid, rights, controlType);
         CreateAndVerifyNamedPipe(GetRandomName(), security, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, inheritability, 0).Dispose();
     }
 }
Example #55
0
        public void ValidArgumentCombinations_NonExecute(
            string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability)
        {
            // Map doesn't exist
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity))
            {
                ValidateMemoryMappedFile(mmf, capacity);
            }
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access))
            {
                ValidateMemoryMappedFile(mmf, capacity, access);
            }
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability))
            {
                ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
            }

            // Map does exist (CreateNew)
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity))
                using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity))
                {
                    ValidateMemoryMappedFile(mmf2, capacity);
                }
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access))
                using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access))
                {
                    ValidateMemoryMappedFile(mmf2, capacity, access);
                }
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability))
                using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability))
                {
                    ValidateMemoryMappedFile(mmf2, capacity, access, inheritability);
                }

            // Map does exist (CreateFromFile)
            using (TempFile file = new TempFile(GetTestFilePath(), capacity))
                using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName))
                    using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity))
                    {
                        ValidateMemoryMappedFile(mmf2, capacity);
                    }
            using (TempFile file = new TempFile(GetTestFilePath(), capacity))
                using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, capacity, access))
                    using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateOrOpen(mapName, capacity, access))
                    {
                        ValidateMemoryMappedFile(mmf2, capacity, access);
                    }
        }
        public void ValidArgumentCombinations(
            string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability)
        {
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity))
            {
                ValidateMemoryMappedFile(mmf, capacity);
            }

            using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access))
            {
                ValidateMemoryMappedFile(mmf, capacity, access);
            }

            using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability))
            {
                ValidateMemoryMappedFile(mmf, capacity, access, inheritability);
            }
        }
Example #57
0
 public void VerifyException <EXCTYPE>(String strLoc, String mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) where EXCTYPE : Exception
 {
     iCountTestcases++;
     try
     {
         using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity, access, options, inheritability))
         {
             iCountErrors++;
             Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
         }
     }
     catch (EXCTYPE)
     {
         //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
     }
     catch (Exception ex)
     {
         iCountErrors++;
         Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
     }
 }
Example #58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PipeClientWithCallback"/> class.
 /// </summary>
 /// <param name="serverName">The name of the server to connect to.</param>
 /// <param name="pipeName">The name of the pipe.</param>
 /// <param name="handlerFactoryFunc">A factory function to provide the handler implementation.</param>
 /// <param name="options">One of the enumeration values that determines how to open or create the pipe.</param>
 /// <param name="impersonationLevel">One of the enumeration values that determines the security impersonation level.</param>
 /// <param name="inheritability">One of the enumeration values that determines whether the underlying handle will be inheritable by child processes.</param>
 public PipeClientWithCallback(string serverName, string pipeName, Func <THandling> handlerFactoryFunc, PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability)
 {
     this.pipeName           = pipeName;
     this.serverName         = serverName;
     this.handlerFactoryFunc = handlerFactoryFunc;
     this.options            = options;
     this.impersonationLevel = impersonationLevel;
     this.inheritability     = inheritability;
 }
Example #59
0
        public static MemoryMappedFile CreateFromFile(FileStream fileStream, string mapName, long capacity,
                                                      MemoryMappedFileAccess access,
                                                      HandleInheritability inheritability, bool leaveOpen)
        {
            if (fileStream == null)
            {
                throw new ArgumentNullException("fileStream", SR.ArgumentNull_FileStream);
            }

            if (mapName != null && mapName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_MapNameEmptyString);
            }

            if (capacity < 0)
            {
                throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_PositiveOrDefaultCapacityRequired);
            }

            if (capacity == 0 && fileStream.Length == 0)
            {
                throw new ArgumentException(SR.Argument_EmptyFile);
            }

            if (access < MemoryMappedFileAccess.ReadWrite ||
                access > MemoryMappedFileAccess.ReadWriteExecute)
            {
                throw new ArgumentOutOfRangeException("access");
            }

            if (access == MemoryMappedFileAccess.Write)
            {
                throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access");
            }

            if (access == MemoryMappedFileAccess.Read && capacity > fileStream.Length)
            {
                throw new ArgumentException(SR.Argument_ReadAccessWithLargeCapacity);
            }

            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException("inheritability");
            }

            // flush any bytes written to the FileStream buffer so that we can see them in our MemoryMappedFile
            fileStream.Flush();

            if (capacity == DefaultSize)
            {
                capacity = fileStream.Length;
            }

            // one can always create a small view if they do not want to map an entire file
            if (fileStream.Length > capacity)
            {
                throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityGEFileSizeRequired);
            }

            SafeMemoryMappedFileHandle handle = CreateCore(fileStream, mapName, inheritability,
                                                           access, MemoryMappedFileOptions.None, capacity);

            return(new MemoryMappedFile(handle, fileStream, leaveOpen));
        }
 /// <summary>Initializes a new instance of the <see cref="AnonymousPipeServerStreamAdapter" /> class with the specified pipe direction, inheritability mode, buffer size, and pipe security.</summary>
 /// <param name="direction">One of the enumeration values that determines the direction of the pipe.Anonymous pipes can only be in one direction, so <paramref name="direction" /> cannot be set to <see cref="F:System.IO.Pipes.PipeDirection.InOut" />.</param>
 /// <param name="inheritability">One of the enumeration values that determines whether the underlying handle can be inherited by child processes.</param>
 /// <param name="bufferSize">The size of the buffer. This value must be greater than or equal to 0. </param>
 /// <param name="pipeSecurity">An object that determines the access control and audit security for the pipe.</param>
 /// <exception cref="T:System.ArgumentOutOfRangeException">
 /// <paramref name="inheritability" /> is not set to either <see cref="F:System.IO.HandleInheritability.None" /> or <see cref="F:System.IO.HandleInheritability.Inheritable" />.-or-
 /// <paramref name="bufferSize" /> is less than 0.</exception>
 /// <exception cref="T:System.NotSupportedException">
 /// <paramref name="direction" /> is set to <see cref="F:System.IO.Pipes.PipeDirection.InOut" />.</exception>
 public AnonymousPipeServerStreamAdapter(PipeDirection direction, HandleInheritability inheritability, int bufferSize, PipeSecurity pipeSecurity)
     : this(new AnonymousPipeServerStream(direction, inheritability, bufferSize, pipeSecurity))
 {
 }