コード例 #1
0
ファイル: Interop.Poll.cs プロジェクト: Czapek83/corefx
        /// <summary>
        /// Polls a File Descriptor for the passed in flags.
        /// </summary>
        /// <param name="fd">The descriptor to poll</param>
        /// <param name="events">The events to poll for</param>
        /// <param name="timeout">The amount of time to wait; -1 for infinite, 0 for immediate return, and a positive number is the number of milliseconds</param>
        /// <param name="triggered">The events that were returned by the poll call. May be PollEvents.POLLNONE in the case of a timeout.</param>
        /// <returns>An error or Error.SUCCESS.</returns>
        internal static unsafe Error Poll(SafeHandle fd, PollEvents events, int timeout, out PollEvents triggered)
        {
            bool gotRef = false;
            try
            {
                fd.DangerousAddRef(ref gotRef);

                var pollEvent = new PollEvent
                {
                    FileDescriptor = fd.DangerousGetHandle().ToInt32(),
                    Events = events,
                };

                uint unused;
                Error err = Poll(&pollEvent, 1, timeout, &unused);
                triggered = pollEvent.TriggeredEvents;
                return err;
            }
            finally
            {
                if (gotRef)
                {
                    fd.DangerousRelease();
                }
            }
        }
コード例 #2
0
        /*
         *  This is to support SSL with no client cert.
         *  Important: safeHandle should not be Disposed during construction of this object.
         *
         *  _SecPkgInfoW in sspi.h
         */
        internal unsafe SecurityPackageInfoClass(SafeHandle safeHandle, int index)
        {
            if (safeHandle.IsInvalid)
            {
                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Info(this, $"Invalid handle: {safeHandle}");
                }
                return;
            }

            IntPtr unmanagedAddress = safeHandle.DangerousGetHandle() + (sizeof(SecurityPackageInfo) * index);

            if (NetEventSource.Log.IsEnabled())
            {
                NetEventSource.Info(this, $"unmanagedAddress: {unmanagedAddress}");
            }

            SecurityPackageInfo *pSecurityPackageInfo = (SecurityPackageInfo *)unmanagedAddress;

            Capabilities = pSecurityPackageInfo->Capabilities;
            Version      = pSecurityPackageInfo->Version;
            RPCID        = pSecurityPackageInfo->RPCID;
            MaxToken     = pSecurityPackageInfo->MaxToken;

            IntPtr unmanagedString;

            unmanagedString = pSecurityPackageInfo->Name;
            if (unmanagedString != IntPtr.Zero)
            {
                Name = Marshal.PtrToStringUni(unmanagedString);
                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Info(this, $"Name: {Name}");
                }
            }

            unmanagedString = pSecurityPackageInfo->Comment;
            if (unmanagedString != IntPtr.Zero)
            {
                Comment = Marshal.PtrToStringUni(unmanagedString);
                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Info(this, $"Comment: {Comment}");
                }
            }

            if (NetEventSource.Log.IsEnabled())
            {
                NetEventSource.Info(this, this.ToString());
            }
        }
コード例 #3
0
        internal NegotiationInfoClass(SafeHandle safeHandle, int negotiationState)
        {
            if (safeHandle.IsInvalid)
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Info(this, $"Invalid handle:{safeHandle}");
                }
                return;
            }

            IntPtr packageInfo = safeHandle.DangerousGetHandle();

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(this, $"packageInfo:{packageInfo} negotiationState:{negotiationState:x}");
            }

            if (negotiationState == Interop.SspiCli.SECPKG_NEGOTIATION_COMPLETE ||
                negotiationState == Interop.SspiCli.SECPKG_NEGOTIATION_OPTIMISTIC)
            {
                string name = null;

                unsafe
                {
                    IntPtr unmanagedString = ((SecurityPackageInfo *)packageInfo)->Name;
                    if (unmanagedString != IntPtr.Zero)
                    {
                        name = Marshal.PtrToStringUni(unmanagedString);
                    }
                }

                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Info(this, $"packageInfo:{packageInfo} negotiationState:{negotiationState:x} name:{name}");
                }

                // An optimization for future string comparisons.
                if (string.Compare(name, Kerberos, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AuthenticationPackage = Kerberos;
                }
                else if (string.Compare(name, NTLM, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AuthenticationPackage = NTLM;
                }
                else
                {
                    AuthenticationPackage = name;
                }
            }
        }
コード例 #4
0
 private void AppendExecutionProvider(NativeOnnxObjectHandle providerFactory)
 {
     unsafe
     {
         bool success = false;
         providerFactory.DangerousAddRef(ref success);
         if (success)
         {
             NativeMethods.ONNXRuntimeSessionOptionsAppendExecutionProvider(_nativeOption.DangerousGetHandle(), providerFactory.DangerousGetHandle());
             providerFactory.DangerousRelease();
         }
     }
 }
コード例 #5
0
            public EPollAsyncContext(EPollThread thread, SafeHandle handle)
            {
                _epoll      = thread;
                _writeQueue = new Queue(thread);
                _readQueue  = new Queue(thread);
                bool success = false;

                handle.DangerousAddRef(ref success);
                _fd     = handle.DangerousGetHandle().ToInt32();
                _handle = handle;

                _epoll.Control(EPOLL_CTL_ADD, _fd, EPOLLIN | EPOLLOUT | EPOLLET, Key);
            }
コード例 #6
0
 internal static IntPtr SafeHandleAddRef(SafeHandle pHandle, ref bool success)
 {
     if (pHandle == null)
     {
         throw new ArgumentNullException(Environment.GetResourceString("ArgumentNull_SafeHandle"));
     }
     pHandle.DangerousAddRef(ref success);
     if (!success)
     {
         return(IntPtr.Zero);
     }
     return(pHandle.DangerousGetHandle());
 }
コード例 #7
0
        /*
         *  This is to support SSL with no client cert.
         *  Important: safeHandle should not be Disposed during construction of this object.
         *
         *  _SecPkgInfoW in sspi.h
         */
        internal SecurityPackageInfoClass(SafeHandle safeHandle, int index)
        {
            if (safeHandle.IsInvalid)
            {
                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Print("SecurityPackageInfoClass::.ctor() the pointer is invalid: " + (safeHandle.DangerousGetHandle()).ToString("x"));
                }
                return;
            }

            IntPtr unmanagedAddress = IntPtrHelper.Add(safeHandle.DangerousGetHandle(), SecurityPackageInfo.Size * index);

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Print("SecurityPackageInfoClass::.ctor() unmanagedPointer: " + ((long)unmanagedAddress).ToString("x"));
            }

            // TODO (Issue #3114): replace with Marshal.PtrToStructure.
            Capabilities = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf <SecurityPackageInfo>("Capabilities"));
            Version      = Marshal.ReadInt16(unmanagedAddress, (int)Marshal.OffsetOf <SecurityPackageInfo>("Version"));
            RPCID        = Marshal.ReadInt16(unmanagedAddress, (int)Marshal.OffsetOf <SecurityPackageInfo>("RPCID"));
            MaxToken     = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf <SecurityPackageInfo>("MaxToken"));

            IntPtr unmanagedString;

            unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf <SecurityPackageInfo>("Name"));
            if (unmanagedString != IntPtr.Zero)
            {
                Name = Marshal.PtrToStringUni(unmanagedString);
                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Print("Name: " + Name);
                }
            }

            unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf <SecurityPackageInfo>("Comment"));
            if (unmanagedString != IntPtr.Zero)
            {
                Comment = Marshal.PtrToStringUni(unmanagedString);
                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Print("Comment: " + Comment);
                }
            }

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Print("SecurityPackageInfoClass::.ctor(): " + ToString());
            }
        }
コード例 #8
0
        /*
         *  This is to support SSL with no client cert.
         *  Important: safeHandle should not be Disposed during construction of this object.
         *
         *  _SecPkgInfoW in sspi.h
         */
        internal SecurityPackageInfoClass(SafeHandle safeHandle, int index)
        {
            if (safeHandle.IsInvalid)
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Info(this, $"Invalid handle: {safeHandle}");
                }
                return;
            }

            IntPtr unmanagedAddress = IntPtrHelper.Add(safeHandle.DangerousGetHandle(), SecurityPackageInfo.Size * index);

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(this, $"unmanagedAddress: {unmanagedAddress}");
            }

            // TODO (Issue #3114): replace with Marshal.PtrToStructure.
            Capabilities = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf <SecurityPackageInfo>("Capabilities"));
            Version      = Marshal.ReadInt16(unmanagedAddress, (int)Marshal.OffsetOf <SecurityPackageInfo>("Version"));
            RPCID        = Marshal.ReadInt16(unmanagedAddress, (int)Marshal.OffsetOf <SecurityPackageInfo>("RPCID"));
            MaxToken     = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf <SecurityPackageInfo>("MaxToken"));

            IntPtr unmanagedString;

            unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf <SecurityPackageInfo>("Name"));
            if (unmanagedString != IntPtr.Zero)
            {
                Name = Marshal.PtrToStringUni(unmanagedString);
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Info(this, $"Name: {Name}");
                }
            }

            unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf <SecurityPackageInfo>("Comment"));
            if (unmanagedString != IntPtr.Zero)
            {
                Comment = Marshal.PtrToStringUni(unmanagedString);
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Info(this, $"Comment: {Comment}");
                }
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(this, this.ToString());
            }
        }
コード例 #9
0
        private unsafe IAsyncResult BeginReadCore(byte[] array, int offset, int count, AsyncCallback userCallback, Object stateObject)
        {
            CheckParametersForBegin(array, offset, count);

            AsyncFileStream_AsyncResult asyncResult = new AsyncFileStream_AsyncResult(userCallback, stateObject, false);

            if (count == 0)
            {
                asyncResult.SignalCompleted();
            }
            else
            {
                // Keep the array in one location in memory until the OS writes the
                // relevant data into the array.  Free GCHandle later.
                asyncResult.PinBuffer(array);

                fixed(byte *p = array)
                {
                    int  numBytesRead = 0;
                    bool res;

                    res = Native.ReadFile(m_handle.DangerousGetHandle(), p + offset, count, out numBytesRead, asyncResult.OverlappedPtr);
                    if (res == false)
                    {
                        if (HandleErrorSituation("BeginRead", false))
                        {
                            asyncResult.SignalCompleted();
                        }
                        else
                        {
                            m_outstandingRequests.Add(asyncResult);
                        }
                    }
                }
            }

            return(asyncResult);
        }
コード例 #10
0
ファイル: Interop.cs プロジェクト: JohnXi001/iot-1
        public static unsafe int Read(SafeHandle handle, Span <byte> buffer)
        {
            fixed(byte *b = buffer)
            {
                int bytesRead = Interop.SocketRead((int)handle.DangerousGetHandle(), b, buffer.Length);

                if (bytesRead < 0)
                {
                    throw new IOException("`read` operation failed");
                }

                return(bytesRead);
            }
        }
コード例 #11
0
        internal static bool Cancel(SafeHandle safeHandle, out MonoIOError error)
        {
            bool release = false;

            try {
                safeHandle.DangerousAddRef(ref release);
                return(Cancel_internal(safeHandle.DangerousGetHandle(), out error));
            } finally {
                if (release)
                {
                    safeHandle.DangerousRelease();
                }
            }
        }
コード例 #12
0
        public static byte[] GetSignature(this SignerInfo signerInfo)
        {
            var        field            = typeof(SignerInfo).GetField("m_pbCmsgSignerInfo", BindingFlags.Instance | BindingFlags.NonPublic);
            SafeHandle pbCmsgSignerInfo = (SafeHandle)field.GetValue(signerInfo);

            byte[] ret;
            unsafe
            {
                CMSG_SIGNER_INFO *ptr = (CMSG_SIGNER_INFO *)pbCmsgSignerInfo.DangerousGetHandle();
                ret = new byte[ptr->EncryptedHash.cbData];
                Marshal.Copy(ptr->EncryptedHash.pbData, ret, 0, ret.Length);
                return(ret);
            }
        }
コード例 #13
0
        private static bool IsAdministrator(SafeHandle hTokenToCheck)
        {
            var token = hTokenToCheck.DangerousGetHandle();

            if (token == IntPtr.Zero)
            {
                return(false);
            }

            using var id = new WindowsIdentity(token);
            var principal = new WindowsPrincipal(id);

            return(principal.IsInRole(WindowsBuiltInRole.Administrator));
        }
コード例 #14
0
ファイル: MonoIO.cs プロジェクト: Tsalex71/mono-1
        public static MonoFileType GetFileType(SafeHandle safeHandle, out MonoIOError error)
        {
            bool release = false;

            try {
                safeHandle.DangerousAddRef(ref release);
                return(GetFileType(safeHandle.DangerousGetHandle(), out error));
            } finally {
                if (release)
                {
                    safeHandle.DangerousRelease();
                }
            }
        }
コード例 #15
0
        void EnsureRecordBuffer(uint bytes)
        {
            if (bytes <= currentBufferSize)
            {
                return;
            }

            bufferHandle.Close();
            currentBufferSize = bytes;
            bufferHandle      = SafeHGlobalHandleCritical.AllocHGlobal(currentBufferSize);

            record.pbMDData    = bufferHandle.DangerousGetHandle();
            record.dwMDDataLen = currentBufferSize;
        }
コード例 #16
0
        public static unsafe void Write(SafeHandle handle, byte* buffer, int length)
        {
            int totalBytesWritten = 0;
            while (totalBytesWritten < length)
            {
                int bytesWritten = Interop.SocketWrite((int)handle.DangerousGetHandle(), buffer, length);
                if (bytesWritten < 0)
                {
                    throw new IOException("`write` operation failed");
                }

                totalBytesWritten += bytesWritten;
            }
        }
コード例 #17
0
    private ThreadPoolBoundHandle CreateThreadPoolBoundHandle(SafeHandle handle, [CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0)
    {
        handle = handle ?? HandleFactory.CreateAsyncFileHandleForWrite(GetTestFilePath(null, memberName, lineNumber));

        try
        {
            return(ThreadPoolBoundHandle.BindHandle(handle));
        }
        catch (ArgumentException ex) when(ex.GetType() == typeof(ArgumentException))
        {
            // TODO: Remove this try/catch, which is intended to help with debugging https://github.com/dotnet/corefx/issues/18058
            throw new ArgumentException("Handle value: " + handle.DangerousGetHandle(), ex.ParamName, ex);
        }
    }
コード例 #18
0
        private unsafe void OpenFileViewAccessor(string path, Action <IntPtr, long, Action> callback)
        {
            if (callback == null || !File.Exists(path))
            {
                response.StatusCode = 404;
                return;
            }
            MemoryMappedFile         mmf  = null;
            MemoryMappedViewAccessor mmva = null;
            Action closeMmf = () =>
            {
                if (mmva != null)
                {
                    mmva.Dispose();
                    mmva = null;
                }
                if (mmf != null)
                {
                    mmf.Dispose();
                    mmf = null;
                }
            };
            bool immediate_shutdown = false;

            try
            {
                mmf = MemoryMappedFile.CreateFromFile(path, FileMode.Open);
                long totalcount = FileAuxiliary.GetFileLength64(path);
                mmva = mmf.CreateViewAccessor(0, totalcount, MemoryMappedFileAccess.ReadWrite);
                SafeHandle handle = mmva.SafeMemoryMappedViewHandle;
                if (handle.IsInvalid)
                {
                    immediate_shutdown  = true;
                    response.StatusCode = 503;
                }
                else
                {
                    callback(handle.DangerousGetHandle(), totalcount, closeMmf);
                }
            }
            catch (Exception)
            {
                immediate_shutdown  = true;
                response.StatusCode = 500;
            }
            if (immediate_shutdown)
            {
                closeMmf();
            }
        }
コード例 #19
0
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                System.Reflection.FieldInfo fieldInfo = null;
                SafeHandle handle          = (SafeHandle)fieldInfo.GetValue(args[0]);
                IntPtr     dangerousHandle = handle.DangerousGetHandle();
                int?       nullable        = null;
                Console.WriteLine(nullable.Value);
            }

            Console.WriteLine("Hello World!");
            Environment.Exit(0);
        }
コード例 #20
0
ファイル: NegotiationInfo.cs プロジェクト: talha020/corefx
        internal NegotiationInfoClass(SafeHandle safeHandle, int negotiationState)
        {
            if (safeHandle.IsInvalid)
            {
                GlobalLog.Print("NegotiationInfoClass::.ctor() the handle is invalid:" + (safeHandle.DangerousGetHandle()).ToString("x"));
                return;
            }

            IntPtr packageInfo = safeHandle.DangerousGetHandle();

            GlobalLog.Print("NegotiationInfoClass::.ctor() packageInfo:" + packageInfo.ToString("x8") + " negotiationState:" + negotiationState.ToString("x8"));

            const int SECPKG_NEGOTIATION_COMPLETE   = 0;
            const int SECPKG_NEGOTIATION_OPTIMISTIC = 1;

            // const int SECPKG_NEGOTIATION_IN_PROGRESS     = 2;
            // const int SECPKG_NEGOTIATION_DIRECT          = 3;
            // const int SECPKG_NEGOTIATION_TRY_MULTICRED   = 4;

            if (negotiationState == SECPKG_NEGOTIATION_COMPLETE || negotiationState == SECPKG_NEGOTIATION_OPTIMISTIC)
            {
                IntPtr unmanagedString = Marshal.ReadIntPtr(packageInfo, SecurityPackageInfo.NameOffest);
                string name            = null;
                if (unmanagedString != IntPtr.Zero)
                {
                    name = Marshal.PtrToStringUni(unmanagedString);
                }

                GlobalLog.Print("NegotiationInfoClass::.ctor() packageInfo:" + packageInfo.ToString("x8") + " negotiationState:" + negotiationState.ToString("x8") + " name:" + Logging.ObjectToString(name));

                // an optimization for future string comparisons
                if (string.Compare(name, Kerberos, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AuthenticationPackage = Kerberos;
                }
                else if (string.Compare(name, NTLM, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AuthenticationPackage = NTLM;
                }
                else if (string.Compare(name, WDigest, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AuthenticationPackage = WDigest;
                }
                else
                {
                    AuthenticationPackage = name;
                }
            }
        }
コード例 #21
0
        private Advapi32.SERVICE_STATUS_PROCESS ControlService(SafeHandle serviceHandle, uint control)
        {
            IntPtr lpServiceStatus = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Advapi32.SERVICE_STATUS_PROCESS)));

            if (!Advapi32.ControlService(
                    serviceHandle.DangerousGetHandle(),
                    control,
                    lpServiceStatus
                    ))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            return((Advapi32.SERVICE_STATUS_PROCESS)Marshal.PtrToStructure(lpServiceStatus, typeof(Advapi32.SERVICE_STATUS_PROCESS)));
        }
コード例 #22
0
        /// <summary>
        ///     Add a Reference to and Get a Handle.
        /// </summary>
        /// <remarks>
        ///     <para>
        ///         Convenient method to add a reference to a handle before retrieving its wrapped pointer. If a
        ///         reference cannot be added to the handle, an exception is thrown. This follows Microsoft's
        ///         recommended best practice to add a reference to the handle before retrieving its wrapped pointer
        ///         to minimize the risk of handle recycle attacks. You, however, are responsible for releasing the
        ///         reference to the handle after you are done with it, using <c>SafeHandle.DangerousRelease()</c>,
        ///         otherwise you risk a memory leak.
        ///     </para>
        ///     <para>
        ///         This method is the equivalent to calling both <c>SafeHandle.DangerousAddRef()</c> and
        ///         <c>SafeHandle.DangerousGetHandle()</c>, except an exception is thrown if the operation fails. This
        ///         is for convenience if, and only if, you want to treat the failure of this operation as
        ///         exceptional! If you do not want to treat the failure of this operation as exceptional and you
        ///         instead have a non-exceptional back-off routine, do not call this method and perform your back-off
        ///         routine in an exception handler! You're better off simply calling both
        ///         <c>SafeHandle.DangerousAddRef()</c> and <c>SafeHandle.DangerousGetHandle()</c> yourself.
        ///     </para>
        /// </remarks>
        /// <param name="this">
        ///     A handle.
        /// </param>
        /// <returns>
        ///     The handle's wrapped pointer.
        /// </returns>
        /// <exception cref="System.ArgumentException">
        ///     Thrown if the handle is closed, or if the handle is invalid.
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        ///     Thrown if the handle is a null reference.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        ///     Thrown if a reference to the handle could not be added.
        /// </exception>
        internal static IntPtr DangerousAddRefAndGetHandle(this SafeHandle @this)
        {
            var isReferenceAdded = false;

            @this.DangerousAddRef(ref isReferenceAdded);
            if (!isReferenceAdded)
            {
                const string detailMessage = "Unable to add a reference to a handle.";
                throw new InvalidOperationException(detailMessage);
            }

            var pHandle = @this.DangerousGetHandle();

            return(pHandle);
        }
コード例 #23
0
ファイル: IOWrapper.cs プロジェクト: volschin/sdimager
        public static void DiskSetDriveLayoutEx(SafeHandle handle, DRIVE_LAYOUT_INFORMATION_EX layout)
        {
            var  bufSize       = Marshal.SizeOf(layout);
            var  buf           = Marshal.AllocHGlobal(bufSize);
            uint bytesReturned = 0;

            Marshal.StructureToPtr(layout, buf, false);
            var b = DeviceIoControl(handle.DangerousGetHandle(), IOCTL_DISK_SET_DRIVE_LAYOUT_EX, buf, (uint)bufSize, IntPtr.Zero, 0, ref bytesReturned, IntPtr.Zero);

            Marshal.FreeHGlobal(buf);
            if (!b)
            {
                throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
            }
        }
コード例 #24
0
        private static IntPtr HKEYfromRegKey(RegistryKey regKey)
        {
            Type         typeFromHandle = typeof(RegistryKey);
            BindingFlags bindingAttr    = BindingFlags.Instance | BindingFlags.NonPublic;
            FieldInfo    field          = typeFromHandle.GetField("hkey", bindingAttr);

            if (field == null)
            {
                field = typeFromHandle.GetField("_hkey", bindingAttr);
            }

            SafeHandle safeHandle = (SafeHandle)field.GetValue(regKey);

            return(safeHandle.DangerousGetHandle());
        }
コード例 #25
0
        internal NegotiationInfoClass(SafeHandle safeHandle, int negotiationState)
        {
            if (safeHandle.IsInvalid)
            {
                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Print("NegotiationInfoClass::.ctor() the handle is invalid:" + (safeHandle.DangerousGetHandle()).ToString("x"));
                }
                return;
            }

            IntPtr packageInfo = safeHandle.DangerousGetHandle();

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Print("NegotiationInfoClass::.ctor() packageInfo:" + packageInfo.ToString("x8") + " negotiationState:" + negotiationState.ToString("x8"));
            }

            if (negotiationState == Interop.SspiCli.SECPKG_NEGOTIATION_COMPLETE ||
                negotiationState == Interop.SspiCli.SECPKG_NEGOTIATION_OPTIMISTIC)
            {
                IntPtr unmanagedString = Marshal.ReadIntPtr(packageInfo, SecurityPackageInfo.NameOffest);
                string name            = null;
                if (unmanagedString != IntPtr.Zero)
                {
                    name = Marshal.PtrToStringUni(unmanagedString);
                }

                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Print("NegotiationInfoClass::.ctor() packageInfo:" + packageInfo.ToString("x8") + " negotiationState:" + negotiationState.ToString("x8") + " name:" + LoggingHash.ObjectToString(name));
                }

                // An optimization for future string comparisons.
                if (string.Compare(name, Kerberos, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AuthenticationPackage = Kerberos;
                }
                else if (string.Compare(name, NTLM, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    AuthenticationPackage = NTLM;
                }
                else
                {
                    AuthenticationPackage = name;
                }
            }
        }
コード例 #26
0
    public IntPtr MarshalManagedToNative(object ManagedObj)
    {
        if (ManagedObj == null)
        {
            return(IntPtr.Zero);
        }
        SafeHandle[] array   = (SafeHandle[])ManagedObj;
        int          i       = 0;
        bool         success = false;

        try
        {
            for (i = 0; i < array.Length; success = false, i++)
            {
                SafeHandle current = array[i];
                if (current != null && !current.IsClosed && !current.IsInvalid)
                {
                    current.DangerousAddRef(ref success);
                }
            }
            IntPtr result = Marshal.AllocHGlobal(array.Length * IntPtr.Size);
            Marshal.WriteIntPtr(result, 0, GCHandle.ToIntPtr(GCHandle.Alloc(array, GCHandleType.Normal)));
            for (int j = 0; j < array.Length; j++)
            {
                SafeHandle current = array[j];
                if (current == null || current.IsClosed || current.IsInvalid)
                {
                    // the memory for this element was initialized to null by AllocHGlobal
                    continue;
                }
                Marshal.WriteIntPtr(result, (j + 1) * IntPtr.Size, current.DangerousGetHandle());
            }
            return(result + IntPtr.Size);
        }
        catch
        {
            int total = success ? i + 1 : i;
            for (int j = 0; j < total; j++)
            {
                SafeHandle current = array[j];
                if (current != null)
                {
                    current.DangerousRelease();
                }
            }
            throw;
        }
    }
コード例 #27
0
 internal static unsafe Error GetBytesAvailable(SafeHandle socket, int* available)
 {
     bool release = false;
     try
     {
         socket.DangerousAddRef(ref release);
         return DangerousGetBytesAvailable((int)socket.DangerousGetHandle(), available);
     }
     finally
     {
         if (release)
         {
             socket.DangerousRelease();
         }
     }
 }
コード例 #28
0
ファイル: Interop.SendMessage.cs プロジェクト: benpye/corefx
 internal static unsafe Error SendMessage(SafeHandle socket, MessageHeader* messageHeader, SocketFlags flags, long* sent)
 {
     bool release = false;
     try
     {
         socket.DangerousAddRef(ref release);
         return DangerousSendMessage((int)socket.DangerousGetHandle(), messageHeader, flags, sent);
     }
     finally
     {
         if (release)
         {
             socket.DangerousRelease();
         }
     }
 }
コード例 #29
0
 internal static unsafe Error GetIPv6MulticastOption(SafeHandle socket, MulticastOption multicastOption, IPv6MulticastOption* option)
 {
     bool release = false;
     try
     {
         socket.DangerousAddRef(ref release);
         return DangerousGetIPv6MulticastOption((int)socket.DangerousGetHandle(), multicastOption, option);
     }
     finally
     {
         if (release)
         {
             socket.DangerousRelease();
         }
     }
 }
コード例 #30
0
ファイル: Interop.Accept.cs プロジェクト: benpye/corefx
 internal static unsafe Error Accept(SafeHandle socket, byte* socketAddress, int* socketAddressLen, int* acceptedFd)
 {
     bool release = false;
     try
     {
         socket.DangerousAddRef(ref release);
         return DangerousAccept((int)socket.DangerousGetHandle(), socketAddress, socketAddressLen, acceptedFd);
     }
     finally
     {
         if (release)
         {
             socket.DangerousRelease();
         }
     }
 }
コード例 #31
0
ファイル: MonoIO.cs プロジェクト: Tsalex71/mono-1
        public static int Write(SafeHandle safeHandle, byte [] src,
                                int src_offset, int count,
                                out MonoIOError error)
        {
            bool release = false;

            try {
                safeHandle.DangerousAddRef(ref release);
                return(Write(safeHandle.DangerousGetHandle(), src, src_offset, count, out error));
            } finally {
                if (release)
                {
                    safeHandle.DangerousRelease();
                }
            }
        }
コード例 #32
0
ファイル: MonoIO.cs プロジェクト: Tsalex71/mono-1
        public static int Read(SafeHandle safeHandle, byte [] dest,
                               int dest_offset, int count,
                               out MonoIOError error)
        {
            bool release = false;

            try {
                safeHandle.DangerousAddRef(ref release);
                return(Read(safeHandle.DangerousGetHandle(), dest, dest_offset, count, out error));
            } finally {
                if (release)
                {
                    safeHandle.DangerousRelease();
                }
            }
        }
コード例 #33
0
 internal static unsafe Error SetReceiveTimeout(SafeHandle socket, int millisecondsTimeout)
 {
     bool release = false;
     try
     {
         socket.DangerousAddRef(ref release);
         return DangerousSetReceiveTimeout((int)socket.DangerousGetHandle(), millisecondsTimeout);
     }
     finally
     {
         if (release)
         {
             socket.DangerousRelease();
         }
     }
 }
コード例 #34
0
ファイル: Interop.GetSockName.cs プロジェクト: benpye/corefx
 internal static unsafe Error GetSockName(SafeHandle socket, byte* socketAddress, int* socketAddressLen)
 {
     bool release = false;
     try
     {
         socket.DangerousAddRef(ref release);
         return DangerousGetSockName((int)socket.DangerousGetHandle(), socketAddress, socketAddressLen);
     }
     finally
     {
         if (release)
         {
             socket.DangerousRelease();
         }
     }
 }
コード例 #35
0
ファイル: Interop.SetSockOpt.cs プロジェクト: benpye/corefx
 internal static unsafe Error SetSockOpt(SafeHandle socket, SocketOptionLevel optionLevel, SocketOptionName optionName, byte* optionValue, int optionLen)
 {
     bool release = false;
     try
     {
         socket.DangerousAddRef(ref release);
         return DangerousSetSockOpt((int)socket.DangerousGetHandle(), optionLevel, optionName, optionValue, optionLen);
     }
     finally
     {
         if (release)
         {
             socket.DangerousRelease();
         }
     }
 }
コード例 #36
0
ファイル: Interop.Shutdown.cs プロジェクト: benpye/corefx
 internal static Error Shutdown(SafeHandle socket, SocketShutdown how)
 {
     bool release = false;
     try
     {
         socket.DangerousAddRef(ref release);
         return DangerousShutdown((int)socket.DangerousGetHandle(), how);
     }
     finally
     {
         if (release)
         {
             socket.DangerousRelease();
         }
     }
 }
コード例 #37
0
ファイル: Interop.SocketEvent.cs プロジェクト: benpye/corefx
 internal static Error TryChangeSocketEventRegistration(int port, SafeHandle socket, SocketEvents currentEvents, SocketEvents newEvents, IntPtr data)
 {
     bool release = false;
     try
     {
         socket.DangerousAddRef(ref release);
         return DangerousTryChangeSocketEventRegistration(port, (int)socket.DangerousGetHandle(), currentEvents, newEvents, data);
     }
     finally
     {
         if (release)
         {
             socket.DangerousRelease();
         }
     }
 }
コード例 #38
0
ファイル: MonoIO.cs プロジェクト: Tsalex71/mono-1
        public static long Seek(SafeHandle safeHandle, long offset,
                                SeekOrigin origin,
                                out MonoIOError error)
        {
            bool release = false;

            try {
                safeHandle.DangerousAddRef(ref release);
                return(Seek(safeHandle.DangerousGetHandle(), offset, origin, out error));
            } finally {
                if (release)
                {
                    safeHandle.DangerousRelease();
                }
            }
        }
コード例 #39
0
ファイル: Interop.Listen.cs プロジェクト: benpye/corefx
 internal static Error Listen(SafeHandle socket, int backlog)
 {
     bool release = false;
     try
     {
         socket.DangerousAddRef(ref release);
         return DangerousListen((int)socket.DangerousGetHandle(), backlog);
     }
     finally
     {
         if (release)
         {
             socket.DangerousRelease();
         }
     }
 }
コード例 #40
0
ファイル: MonoIO.cs プロジェクト: Tsalex71/mono-1
        public static bool SetLength(SafeHandle safeHandle,
                                     long length,
                                     out MonoIOError error)
        {
            bool release = false;

            try {
                safeHandle.DangerousAddRef(ref release);
                return(SetLength(safeHandle.DangerousGetHandle(), length, out error));
            } finally {
                if (release)
                {
                    safeHandle.DangerousRelease();
                }
            }
        }
コード例 #41
0
ファイル: MonoIO.cs プロジェクト: Tsalex71/mono-1
        public static void Unlock(SafeHandle safeHandle,
                                  long position, long length,
                                  out MonoIOError error)
        {
            bool release = false;

            try {
                safeHandle.DangerousAddRef(ref release);
                Unlock(safeHandle.DangerousGetHandle(), position, length, out error);
            } finally {
                if (release)
                {
                    safeHandle.DangerousRelease();
                }
            }
        }
コード例 #42
0
 internal static unsafe Error GetSocketErrorOption(SafeHandle socket, Error* socketError)
 {
     bool release = false;
     try
     {
         socket.DangerousAddRef(ref release);
         return DangerousGetSocketErrorOption((int)socket.DangerousGetHandle(), socketError);
     }
     finally
     {
         if (release)
         {
             socket.DangerousRelease();
         }
     }
 }
コード例 #43
0
ファイル: MSCorEEFacts.cs プロジェクト: jmelosegui/pinvoke
    public static IEnumerable<string> GetProcessRuntimes(ICLRMetaHost host, SafeHandle hProcess)
    {
        if (host != null)
        {
            var buffer = new StringBuilder(1024);
            IEnumUnknown ppEnumerator = host.EnumerateLoadedRuntimes(hProcess.DangerousGetHandle());
            return ppEnumerator.Cast<ICLRRuntimeInfo>().Select(rti =>
            {
                var bufferLength = (uint)buffer.Capacity;
                rti.GetVersionString(buffer, ref bufferLength);
                return buffer.ToString(0, (int)bufferLength - 1);
            }).ToList();
        }
        else
        {
            string buffer = GetVersionFromProcess(hProcess);
            if (buffer != null)
            {
                return new[] { buffer };
            }
        }

        return Enumerable.Empty<string>();
    }