Ejemplo n.º 1
0
        private static List <Process> LoadChildProcesses(IProgress <string> progress)
        {
            progress.Report(ReallyStopDebugger.Resources.ProgressReport_1);
            var childProcesses = WindowsNative.GetChildProcesses(WindowsNative.GetCurrentProcess().SafeGetProcessId());

            return(childProcesses);
        }
 public void Dispose()
 {
     if (_disableSuccess)
     {
         WindowsNative.SetThreadErrorMode(_oldMode, out _);
     }
 }
                public static MediaInsertionPromptGuard Enter()
                {
                    MediaInsertionPromptGuard prompt = default;

                    prompt._disableSuccess = WindowsNative.SetThreadErrorMode(WindowsNative.SEM_FAILCRITICALERRORS, out prompt._oldMode);
                    return(prompt);
                }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InputDevice"/> class with the specified <see cref="DeviceDescriptor"/> and parent <see cref="DeviceManager"/>
        /// </summary>
        /// <param name="descriptor">Describes the HID compliant device to open a connection to</param>
        /// <param name="manager">The parent <see cref="DeviceManager"/> of this <see cref="InputDevice"/></param>
        public InputDevice(DeviceDescriptor descriptor, DeviceManager manager)
        {
            this.descriptor = descriptor;
            this.manager    = manager;

            Open();

            // If the device succeeded in opening, get the attributes and capabilities
            if (open)
            {
                Connected = true;

                WindowsNative.HIDD_ATTRIBUTES attr = new WindowsNative.HIDD_ATTRIBUTES();
                attr.Size = Marshal.SizeOf(attr);
                WindowsNative.HidD_GetAttributes(hid, ref attr);

                capabilities = default(WindowsNative.HIDP_CAPS);
                IntPtr ptr = default(IntPtr);

                // This shouldn't fail, but no big deal if it does
                // The device will just end up getting garbage collected if it has invalid vid/pid
                if (WindowsNative.HidD_GetPreparsedData(hid, ref ptr))
                {
                    WindowsNative.HidP_GetCaps(ptr, ref capabilities);
                    WindowsNative.HidD_FreePreparsedData(ptr);
                }

                Close();

                this.descriptor.SetIDSFromAttributes(attr);
            }
        }
 public static void GetSpace(IAbsoluteDirectoryPath.Impl path, out long availableBytes, out long totalBytes, out long freeBytes)
 {
     using (MediaInsertionPromptGuard.Enter()) {
         if (!WindowsNative.GetDiskFreeSpaceEx(path.PathExport, out availableBytes, out totalBytes, out freeBytes))
         {
             throw GetLastWin32ErrorException(path);
         }
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Closes the connection to the device
        /// </summary>
        private void Close()
        {
            // I think this first call is only for Vista+, but do we really have to care about XP?
            WindowsNative.CancelIoEx(hid, IntPtr.Zero);
            WindowsNative.CloseHandle(hid);

            hid  = new IntPtr(-1);
            open = false;
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Reads bytes from the device
        /// </summary>
        /// <returns>The read bytes</returns>
        private byte[] Read()
        {
            if (!open)
            {
                Open();
            }

            byte[] bytes = new byte[] { };

            // I'm not sure why a controller wouldn't be able to send anything, but better safe than sorry
            if (capabilities.InputReportByteLength <= 0)
            {
                return(bytes);
            }

            // Create return array and allocate unmanaged array for native calls
            bytes = new byte[capabilities.InputReportByteLength];
            IntPtr buffer = Marshal.AllocHGlobal(bytes.Length);

            try
            {
                // Just a windows native struct
                NativeOverlapped overlapped = new NativeOverlapped();

                if (!WindowsNative.ReadFile(hid, buffer, (uint)bytes.Length, out uint read, ref overlapped))
                {
                    // If the I/O read failed, get the error
                    int err = Marshal.GetLastWin32Error();

                    // Error 1167 means the device isn't connected
                    if (err == 1167)
                    {
                        Close();
                        Connected = false;
                        manager.RemoveDevice(this);
                        OnDisconnect?.Invoke();
                    }
                    else
                    {
                        // If it's an unknown error, throw it
                        throw new Exception("Error #" + err + ": " + new Win32Exception(err).Message);
                    }
                }

                Marshal.Copy(buffer, bytes, 0, (int)read);
            }
            finally
            {
                // Using finally to guarantee this is freed to prevent memory leaks
                Marshal.FreeHGlobal(buffer);
            }

            return(bytes);
        }
Ejemplo n.º 8
0
 unsafe static char *memmove(char *dest, char *src, UIntPtr count)
 {
     if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
     {
         return(WindowsNative.memmoveWin(dest, src, count));
     }
     else
     {
         Buffer.MemoryCopy((void *)src, (void *)dest, count.ToUInt32(), count.ToUInt32());
         return(dest);
     }
 }
Ejemplo n.º 9
0
        private static bool InitializeDotNetFramework(string userSpecifiedPath)
        {
            string path      = userSpecifiedPath;
            bool   isWindows = IsWindows();

            if (path == null && isWindows)
            {
                // in net45, librdkafka.dll is not in the process directory, we have to load it manually
                // and also search in the same folder for its dependencies (LOAD_WITH_ALTERED_SEARCH_PATH)
                var is64          = IntPtr.Size == 8;
                var baseUri       = new Uri(Assembly.GetExecutingAssembly().GetName().EscapedCodeBase);
                var baseDirectory = Path.GetDirectoryName(baseUri.LocalPath);
                var dllDirectory  = Path.Combine(
                    baseDirectory,
                    is64
                        ? Path.Combine("librdkafka", "x64")
                        : Path.Combine("librdkafka", "x86"));
                path = Path.Combine(dllDirectory, "librdkafka.dll");

                if (!File.Exists(path))
                {
                    dllDirectory = Path.Combine(
                        baseDirectory,
                        is64
                            ? @"runtimes\win7-x64\native"
                            : @"runtimes\win7-x86\native");
                    path = Path.Combine(dllDirectory, "librdkafka.dll");
                }
            }

            if (isWindows && WindowsNative.LoadLibraryEx(
                    path,
                    IntPtr.Zero,
                    WindowsNative.LoadLibraryFlags.LOAD_WITH_ALTERED_SEARCH_PATH) == IntPtr.Zero)
            {
                // catch the last win32 error by default and keep the associated default message
                var win32Exception    = new Win32Exception();
                var additionalMessage =
                    $"Error while loading librdkafka.dll or its dependencies from {path}. " +
                    $"Check the directory exists, if not check your deployment process. " +
                    $"You can also load the library and its dependencies by yourself " +
                    $"before any call to Confluent.Kafka";

                throw new InvalidOperationException(additionalMessage, win32Exception);
            }

            return(SetDelegates(typeof(NativeMethods.NativeMethods)));
        }
            public static unsafe string GetFileSystem(IAbsoluteDirectoryPath.Impl rootDir)
            {
                // rootDir must be a symlink or root drive

                const int MAX_LENGTH = 261; // MAX_PATH + 1

                char *fileSystemName = stackalloc char[MAX_LENGTH];

                using (MediaInsertionPromptGuard.Enter()) {
                    if (!WindowsNative.GetVolumeInformation(rootDir.PathExportWithTrailingSeparator, null, 0, null, null, out int fileSystemFlags, fileSystemName, MAX_LENGTH))
                    {
                        throw GetLastWin32ErrorException(rootDir);
                    }
                }

                return(new string(fileSystemName));
            }
Ejemplo n.º 11
0
        /// <summary>
        /// Opens the connection to the device
        /// </summary>
        private void Open()
        {
            if (open)
            {
                return;
            }

            WindowsNative.SECURITY_ATTRIBUTES sec = new WindowsNative.SECURITY_ATTRIBUTES();
            sec.SetupDefaults();
            sec.bInheritHandle = true;

            // 3 = FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING
            // 2147483648 = GENERIC_READ
            hid = WindowsNative.CreateFile(descriptor.Path, 2147483648, 3, ref sec, 3, 0, 0);

            // Check that it actually succeeded before setting open
            if (hid.ToInt32() != -1)
            {
                open = true;
            }
        }
Ejemplo n.º 12
0
        private void StopServer()
        {
            _requestExit = true;
            if (ClrDetection.IsMono())
            {
                Process.Start("kill", "-SIGTERM " + _staxelProcess.Id);
            }
            else
            {
                try {
                    WindowsNative.AttachConsole((uint)_staxelProcess.Id);
                    WindowsNative.SetConsoleCtrlHandler(null, true);

                    WindowsNative.GenerateConsoleCtrlEvent(WindowsNative.CTRL_C_EVENT, 0);

                    WindowsNative.FreeConsole();
                    WindowsNative.SetConsoleCtrlHandler(null, false);
                } catch {
                    // ignore
                }
            }
        }
 protected override bool ReleaseHandle()
 {
     return(WindowsNative.DeleteObject(this.handle));
 }
Ejemplo n.º 14
0
 public static DriveType GetDriveType(IAbsoluteDirectoryPath.Impl path) => WindowsNative.GetDriveType(path.PathExportWithTrailingSeparator);
Ejemplo n.º 15
0
        public static bool Initialize(string userSpecifiedPath)
        {
            lock (loadLockObj)
            {
                if (isInitialized)
                {
                    return(false);
                }

                isInitialized = false;

#if NET45 || NET46 || NET47
                string path = userSpecifiedPath;
                if (path == null)
                {
                    // in net45, librdkafka.dll is not in the process directory, we have to load it manually
                    // and also search in the same folder for its dependencies (LOAD_WITH_ALTERED_SEARCH_PATH)
                    var is64          = IntPtr.Size == 8;
                    var baseUri       = new Uri(Assembly.GetExecutingAssembly().GetName().EscapedCodeBase);
                    var baseDirectory = Path.GetDirectoryName(baseUri.LocalPath);
                    var dllDirectory  = Path.Combine(
                        baseDirectory,
                        is64
                            ? Path.Combine("librdkafka", "x64")
                            : Path.Combine("librdkafka", "x86"));
                    path = Path.Combine(dllDirectory, "librdkafka.dll");

                    if (!File.Exists(path))
                    {
                        dllDirectory = Path.Combine(
                            baseDirectory,
                            is64
                                ? @"runtimes\win7-x64\native"
                                : @"runtimes\win7-x86\native");
                        path = Path.Combine(dllDirectory, "librdkafka.dll");
                    }
                }

                if (WindowsNative.LoadLibraryEx(path, IntPtr.Zero, WindowsNative.LoadLibraryFlags.LOAD_WITH_ALTERED_SEARCH_PATH) == IntPtr.Zero)
                {
                    // catch the last win32 error by default and keep the associated default message
                    var win32Exception    = new Win32Exception();
                    var additionalMessage =
                        $"Error while loading librdkafka.dll or its dependencies from {path}. " +
                        $"Check the directory exists, if not check your deployment process. " +
                        $"You can also load the library and its dependencies by yourself " +
                        $"before any call to Confluent.Kafka";

                    throw new InvalidOperationException(additionalMessage, win32Exception);
                }

                isInitialized = SetDelegates(typeof(NativeMethods.NativeMethods));
#else
                const int RTLD_NOW = 2;

                var nativeMethodTypes = new List <Type>();

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    if (userSpecifiedPath != null)
                    {
                        if (WindowsNative.LoadLibraryEx(userSpecifiedPath, IntPtr.Zero, WindowsNative.LoadLibraryFlags.LOAD_WITH_ALTERED_SEARCH_PATH) == IntPtr.Zero)
                        {
                            // TODO: The Win32Exception class is not available in .NET Standard, which is the easy way to get the message string corresponding to
                            // a win32 error. FormatMessage is not straightforward to p/invoke, so leaving this as a job for another day.
                            throw new InvalidOperationException($"Failed to load librdkafka at location '{userSpecifiedPath}'. Win32 error: {Marshal.GetLastWin32Error()}");
                        }
                    }

                    nativeMethodTypes.Add(typeof(NativeMethods.NativeMethods));
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    if (userSpecifiedPath != null)
                    {
                        if (PosixNative.dlopen(userSpecifiedPath, RTLD_NOW) == IntPtr.Zero)
                        {
                            throw new InvalidOperationException($"Failed to load librdkafka at location '{userSpecifiedPath}'. dlerror: '{PosixNative.LastError}'.");
                        }
                    }

                    nativeMethodTypes.Add(typeof(NativeMethods.NativeMethods));
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    if (userSpecifiedPath != null)
                    {
                        if (PosixNative.dlopen(userSpecifiedPath, RTLD_NOW) == IntPtr.Zero)
                        {
                            throw new InvalidOperationException($"Failed to load librdkafka at location '{userSpecifiedPath}'. dlerror: '{PosixNative.LastError}'.");
                        }

                        nativeMethodTypes.Add(typeof(NativeMethods.NativeMethods));
                    }
                    else
                    {
                        nativeMethodTypes.Add(typeof(NativeMethods.NativeMethods));
                        nativeMethodTypes.Add(typeof(NativeMethods.NativeMethods_Debian9));
                    }
                }
                else
                {
                    throw new InvalidOperationException($"Unsupported platform: {RuntimeInformation.OSDescription}");
                }

                foreach (var t in nativeMethodTypes)
                {
                    isInitialized = SetDelegates(t);
                    if (isInitialized)
                    {
                        break;
                    }
                }
#endif

                if (!isInitialized)
                {
                    throw new DllNotFoundException("Failed to load the librdkafka native library.");
                }

                if ((long)version() < minVersion)
                {
                    throw new FileLoadException($"Invalid librdkafka version {(long)version():x}, expected at least {minVersion:x}");
                }

                isInitialized = true;

                // Protect the _destroy and _destroyMethodInfo objects from garbage collection. This is
                // required since the Producer/Consumer finalizers may reference them, and they might
                // have otherwise been cleaned up at that point. To keep things simple, there is no reference
                // counting / corresponding Free() call - there is negligible overhead in keeping these
                // references around for the lifetime of the process.
                GCHandle.Alloc(_destroy, GCHandleType.Normal);
                GCHandle.Alloc(_destroyMethodInfo, GCHandleType.Normal);

                return(isInitialized);
            }
        }
Ejemplo n.º 16
0
        public AxBorderTextBox()
        {
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true);

            InitializeComponent();

            //_captionPosition = ContentPosition.Left;

            CaptionImageSize     = new Size(16, 16);
            CaptionTextAlignment = HorizontalAlignment.Center;

            _normalStyle = new StateStyle()
            {
                BackColor   = Color.White,
                ForeColor   = Color.Black,
                BorderColor = Color.Black
            };
            _normalStyle.PropertyChanged += (propertyName) => {
                NormalStyleChanged();
                Refresh();
            };

            _hoverStyle = new StateStyle()
            {
                BackColor   = Color.White,
                ForeColor   = Color.Black,
                BorderColor = Color.Black
            };

            _errorStyle = new StateStyle()
            {
                BackColor   = Color.White,
                ForeColor   = Color.Black,
                BorderColor = Color.Black
            };

            _disabledStyle = new StateStyle()
            {
                BackColor   = Color.White,
                ForeColor   = Color.Black,
                BorderColor = Color.Black
            };

            _captionNormalStyle = new StateStyle()
            {
                BackColor   = Color.White,
                ForeColor   = Color.Black,
                BorderColor = Color.Black
            };
            _captionNormalStyle.PropertyChanged += (propertyName) => {
                Refresh();
            };

            Error            = false;
            BorderThickness  = 1;
            Height           = textBox1.Size.Height + BorderPadding * 2;
            textBox1.Resize += (s, e) => AxBorderTextBox_Resize(s, e);

            textBox1.GotFocus += (source, e) => {
                if (string.IsNullOrEmpty(Text))
                {
                    WindowsNative.SendMessage(textBox1.Handle, WindowsNative.EM_SETCUEBANNER, 1, "");
                }
            };

            textBox1.LostFocus += (source, e) => {
                if (string.IsNullOrEmpty(Text) && !string.IsNullOrEmpty(Hint))
                {
                    WindowsNative.SendMessage(textBox1.Handle, WindowsNative.EM_SETCUEBANNER, 1, Hint);
                }
            };

            if (!Error)
            {
                textBox1.ForeColor = NormalStyle.ForeColor;
                textBox1.BackColor = NormalStyle.BackColor;
            }
            else
            {
                textBox1.BackColor = ErrorStyle.BackColor;
                textBox1.ForeColor = ErrorStyle.ForeColor;
            }

            _captionSize = GetCaptionSize();
        }
        public static ProcessOperationException KillProcesses(
            Package package,
            IList processNames,
            bool restrictUser,
            bool restrictChildren,
            bool consoleMode = false)
        {
            var currentProcessName = string.Empty;

            try
            {
                var runningProcesses = restrictUser
                                           ? WindowsNative.GetCurrentUserProcesses()
                                           : Process.GetProcesses().ToList();

                var filteredProcesses =
                    runningProcesses.Join(
                        processNames.Cast <string>(),
                        p => p.SafeGetProcessName().ToLowerInvariant(),
                        n => (n ?? string.Empty).ToLowerInvariant(),
                        (p, n) => p).ToList();

                if (restrictChildren)
                {
                    var childProcesses = WindowsNative.GetChildProcesses(WindowsNative.GetCurrentProcess().SafeGetProcessId());

                    filteredProcesses =
                        (from p in filteredProcesses join c in childProcesses on p.SafeGetProcessId() equals c.SafeGetProcessId() select p).ToList();
                }

                if (!filteredProcesses.Any())
                {
                    return(new ProcessOperationException(ProcessOperationResults.NotFound, new InstanceNotFoundException(Resources.ProcessNotFoundExceptionMessage)));
                }

                foreach (var p in filteredProcesses)
                {
                    currentProcessName = p.SafeGetProcessName();
                    p.Kill();
                }
            }
            catch (Win32Exception ex)
            {
                if (!consoleMode)
                {
                    package.ShowErrorMessage(
                        Resources.ProcessKillError_Win32,
                        Resources.ProcessKillError_Prompt + currentProcessName);
                }

                return(new ProcessOperationException(ProcessOperationResults.Error, ex));
            }
            catch (NotSupportedException ex)
            {
                if (!consoleMode)
                {
                    package.ShowErrorMessage(
                        Resources.ProcessKillError_NotSupported,
                        Resources.ProcessKillError_Prompt + currentProcessName);
                }

                return(new ProcessOperationException(ProcessOperationResults.Error, ex));
            }
            catch (InvalidOperationException ex)
            {
                if (!consoleMode)
                {
                    package.ShowErrorMessage(
                        Resources.ProcessKillError_InvalidOperation,
                        Resources.ProcessKillError_Prompt + currentProcessName);
                }

                return(new ProcessOperationException(ProcessOperationResults.Error, ex));
            }
            catch (Exception ex)
            {
                if (!consoleMode)
                {
                    package.ShowErrorMessage(
                        string.Format(Resources.ProcessKillError_General + ex.Message),
                        Resources.ProcessKillError_Prompt + currentProcessName);
                }

                return(new ProcessOperationException(ProcessOperationResults.Error, ex));
            }

            return(new ProcessOperationException(ProcessOperationResults.Success, null));
        }
 public static string GetProcessPath(Process process)
 {
     return(WindowsNative.GetProcessFilePath(process.SafeGetProcessId()));
 }
Ejemplo n.º 19
0
        private static bool InitializeDotNetCore(string userSpecifiedPath)
        {
            const int RTLD_NOW = 2;

            var nativeMethodTypes = new List <Type>();

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                if (userSpecifiedPath != null)
                {
                    if (WindowsNative.LoadLibraryEx(userSpecifiedPath, IntPtr.Zero, WindowsNative.LoadLibraryFlags.LOAD_WITH_ALTERED_SEARCH_PATH) == IntPtr.Zero)
                    {
                        // TODO: The Win32Exception class is not available in .NET Standard, which is the easy way to get the message string corresponding to
                        // a win32 error. FormatMessage is not straightforward to p/invoke, so leaving this as a job for another day.
                        throw new InvalidOperationException($"Failed to load librdkafka at location '{userSpecifiedPath}'. Win32 error: {Marshal.GetLastWin32Error()}");
                    }
                }

                nativeMethodTypes.Add(typeof(NativeMethods.NativeMethods));
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                if (userSpecifiedPath != null)
                {
                    if (PosixNative.dlopen(userSpecifiedPath, RTLD_NOW) == IntPtr.Zero)
                    {
                        throw new InvalidOperationException($"Failed to load librdkafka at location '{userSpecifiedPath}'. dlerror: '{PosixNative.LastError}'.");
                    }
                }

                nativeMethodTypes.Add(typeof(NativeMethods.NativeMethods));
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                if (userSpecifiedPath != null)
                {
                    if (PosixNative.dlopen(userSpecifiedPath, RTLD_NOW) == IntPtr.Zero)
                    {
                        throw new InvalidOperationException($"Failed to load librdkafka at location '{userSpecifiedPath}'. dlerror: '{PosixNative.LastError}'.");
                    }

                    nativeMethodTypes.Add(typeof(NativeMethods.NativeMethods));
                }
                else
                {
                    nativeMethodTypes.Add(typeof(NativeMethods.NativeMethods));
                    nativeMethodTypes.Add(typeof(NativeMethods.NativeMethods_Debian9));
                }
            }
            else
            {
                throw new InvalidOperationException($"Unsupported platform: {RuntimeInformation.OSDescription}");
            }

            foreach (var t in nativeMethodTypes)
            {
                if (SetDelegates(t))
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 20
0
 protected override bool ReleaseHandle()
 {
     // Marshal.FreeHGlobal wraps LocalFree, so we use the direct call to validate
     return(WindowsNative.LocalFree(this.handle) == IntPtr.Zero);
 }
Ejemplo n.º 21
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return(null);
            }

            if (!(value is Blob blob))
            {
                return(null);
            }

            if (FolderResource.IsLoadingBlob(blob))
            {
                return(null);
            }

            if (targetType == typeof(ImageSource))
            {
                if (blob.Kind == BlobItemKind.Folder)
                {
                    if (blob.Properties.ContainsKey("IsLogsContainer"))
                    {
                        return("azure/metrics".GetImageSource());
                    }

                    if (blob.Properties.ContainsKey("IsSecret"))
                    {
                        return("account/azure.keyvault.secret".GetImageSource());
                    }

                    if (blob.Properties.ContainsKey("IsContainer"))
                    {
                        return("account/azure.blob.container".GetImageSource());
                    }

                    if (blob.Properties.ContainsKey("IsFilesystem"))
                    {
                        return("account/azure.datalake.gen2".GetImageSource());
                    }

                    if (blob.Properties.ContainsKey("IsShare"))
                    {
                        return("account/azure.file".GetImageSource());
                    }


                    return(_folderImageSource);
                }

                return(WindowsNative.HasAssociatedProgram(blob.Name) ? IconManager.FindIconForFilename(blob.Name, false) : null);
            }
            else if (targetType == typeof(Visibility))
            {
                if (blob.IsFile && WindowsNative.HasAssociatedProgram(blob.Name))
                {
                    return(Visibility.Visible);
                }

                return(Visibility.Collapsed);
            }

            return(null);
        }