Example #1
0
        internal bool InitializeJob()
        {
            // Create a job object and add the process to it. We do this to ensure that we can kill the process and
            // all its children in one shot.  Simply killing the process does not kill its children.
            NativeMethods.SECURITY_ATTRIBUTES jobSecAttributes = new NativeMethods.SECURITY_ATTRIBUTES();
            jobSecAttributes.bInheritHandle = true;
            jobSecAttributes.lpSecurityDescriptor = IntPtr.Zero;
            jobSecAttributes.nLength = Marshal.SizeOf(typeof(NativeMethods.SECURITY_ATTRIBUTES));

            IntPtr pointer = NativeMethods.CreateJobObject(ref jobSecAttributes, this.jobName);
            int createJobObjectWin32Error = Marshal.GetLastWin32Error();

            this.SetHandle(pointer);

            if (this.IsInvalid)
            {
                var error = string.Format("In InitializeJob.JobHandle: Failed to SetInformation for job {0} because {1}", this.jobName, createJobObjectWin32Error);
                Debug.WriteLine(error);
            }
            else
            {
                // LimitFlags include JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
                // to terminate all processes associated with the job when the last job handle is closed
                NativeMethods.JOBOBJECT_BASIC_LIMIT_INFORMATION basicInfo = new NativeMethods.JOBOBJECT_BASIC_LIMIT_INFORMATION();

                NativeMethods.JOBOBJECT_EXTENDED_LIMIT_INFORMATION extendedInfo = new NativeMethods.JOBOBJECT_EXTENDED_LIMIT_INFORMATION { BasicLimitInformation = basicInfo };
                extendedInfo.BasicLimitInformation.LimitFlags = NativeMethods.JOB_OBJECT_LIMIT.KILL_ON_JOB_CLOSE;

                int length = Marshal.SizeOf(typeof(NativeMethods.JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
                IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length);
                Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);

                bool result = NativeMethods.SetInformationJobObject(this, NativeMethods.JOBOBJECTINFOCLASS.JobObjectExtendedLimitInformation, ref extendedInfo, length);
                int setInformationJobObjectWin32Error = Marshal.GetLastWin32Error();
                if (!result)
                {
                    //this.logger.LogError("InitializeJob", "JobHandle : Failed to SetInformation for job '{0}' because '{1}'", this.jobName, setInformationJobObjectWin32Error);
                }
                else
                {
                    return true;
                }
            }

            return false;
        }
Example #2
0
 private void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs)
 {
     NativeMethods.SECURITY_ATTRIBUTES sECURITY_ATTRIBUTES = new NativeMethods.SECURITY_ATTRIBUTES();
     sECURITY_ATTRIBUTES.bInheritHandle = true;
     SafeFileHandle safeFileHandle = null;
     try
     {
         if (parentInputs)
         {
             Process2.CreatePipeWithSecurityAttributes(out childHandle, out safeFileHandle, sECURITY_ATTRIBUTES, 0);
         }
         else
         {
             Process2.CreatePipeWithSecurityAttributes(out safeFileHandle, out childHandle, sECURITY_ATTRIBUTES, 0);
         }
         if (!NativeMethods.DuplicateHandle(new HandleRef(this, NativeMethods.GetCurrentProcess()), safeFileHandle, new HandleRef(this, NativeMethods.GetCurrentProcess()), out parentHandle, 0, false, 2))
         {
             throw new Win32Exception();
         }
     }
     finally
     {
         if (safeFileHandle != null && !safeFileHandle.IsInvalid)
         {
             safeFileHandle.Close();
         }
     }
 }
Example #3
0
        /// <summary>
        /// Creates pipe with full access rights for everyone.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Pipe is already open.</exception>
        /// <exception cref="System.IO.IOException">Cannot create named pipe.</exception>
        public void CreateWithFullAccess()
        {
            if (this.SafeHandle != null) { throw new InvalidOperationException("Pipe is already open."); }

            var sec = new RawSecurityDescriptor(ControlFlags.DiscretionaryAclPresent, null, null, null, null);
            var sa = new NativeMethods.SECURITY_ATTRIBUTES();
            sa.nLength = Marshal.SizeOf(typeof(NativeMethods.SECURITY_ATTRIBUTES));
            sa.bInheritHandle = true;

            byte[] secBinary = new byte[sec.BinaryLength];
            sec.GetBinaryForm(secBinary, 0);
            sa.lpSecurityDescriptor = Marshal.AllocHGlobal(secBinary.Length);
            Marshal.Copy(secBinary, 0, sa.lpSecurityDescriptor, secBinary.Length);

            this.SafeHandle = NativeMethods.CreateNamedPipe(this.FullPipeName, NativeMethods.PIPE_ACCESS_DUPLEX, NativeMethods.PIPE_TYPE_BYTE | NativeMethods.PIPE_READMODE_BYTE | NativeMethods.PIPE_WAIT, NativeMethods.PIPE_UNLIMITED_INSTANCES, 4096, 4096, NativeMethods.NMPWAIT_USE_DEFAULT_WAIT, ref sa);
            if (this.SafeHandle.IsInvalid) { throw new IOException("Cannot create named pipe.", new Win32Exception()); }
        }
Example #4
0
        internal void OpenFile(string fileName)
        {
            NativeMethods.SECURITY_ATTRIBUTES sa = new NativeMethods.SECURITY_ATTRIBUTES();
            try
            {
                unsafe
                {
                    // Disable PREsharp warning about not calling Marshal.GetLastWin32Error,
                    // because we already check the handle for invalid value and
                    // we are not particularly interested in specific Win32 error.

#pragma warning disable 6523

                    long size;

                    using (SafeFileHandle fileHandle = UnsafeNativeMethods.CreateFile(
                               fileName,
                               NativeMethods.GENERIC_READ,
                               NativeMethods.FILE_SHARE_READ,
                               null,
                               NativeMethods.OPEN_EXISTING,
                               0,
                               IntPtr.Zero
                               ))
                    {
                        if (fileHandle.IsInvalid)
                        {
                            Util.ThrowWin32Exception(Marshal.GetLastWin32Error(), fileName);
                        }

                        UnsafeNativeMethods.LARGE_INTEGER fileSize = new UnsafeNativeMethods.LARGE_INTEGER();
                        if (!UnsafeNativeMethods.GetFileSizeEx(fileHandle, ref fileSize))
                        {
                            throw new IOException(SR.Get(SRID.IOExceptionWithFileName, fileName));
                        }

                        size = (long)fileSize.QuadPart;
                        if (size == 0)
                        {
                            throw new FileFormatException(new Uri(fileName));
                        }

                        _mappingHandle = UnsafeNativeMethods.CreateFileMapping(
                            fileHandle,
                            sa,
                            UnsafeNativeMethods.PAGE_READONLY,
                            0,
                            0,
                            null);
                    }

                    if (_mappingHandle.IsInvalid)
                    {
                        throw new IOException(SR.Get(SRID.IOExceptionWithFileName, fileName));
                    }

                    _viewHandle = UnsafeNativeMethods.MapViewOfFileEx(_mappingHandle, UnsafeNativeMethods.FILE_MAP_READ, 0, 0, IntPtr.Zero, IntPtr.Zero);
                    if (_viewHandle.IsInvalid)
                    {
                        throw new IOException(SR.Get(SRID.IOExceptionWithFileName, fileName));
                    }

#pragma warning restore 6523

                    // Initialize() method demands UnmanagedCode permission, and OpenFile() is already marked as critical.

                    new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); //Blessed Assert

                    try
                    {
                        Initialize((byte *)_viewHandle.Memory, size, size, FileAccess.Read);
                    }
                    finally
                    {
                        SecurityPermission.RevertAssert();
                    }
                }
            }
            finally
            {
                sa.Release();
                sa = null;
            }
        }