示例#1
0
 private void Free(IntPtr Ptr)
 => Marshal.FreeCoTaskMem(Ptr);
示例#2
0
        internal static void WinIOError(string str)
        {
            int errorCode = Marshal.GetLastWin32Error();

            WinIOError(errorCode, str);
        }
示例#3
0
 public static IntPtr OffsetOf <T>(string fieldName)
 {
     return(SystemMarshal.OffsetOf <T>(fieldName));
 }
示例#4
0
        private static jthread alloc_thread(JNIEnvHandle jniEnv)
        {
            jniNativeInterface nativeInterface = (jniNativeInterface)Marshal.PtrToStructure(Marshal.ReadIntPtr(jniEnv.Handle), typeof(jniNativeInterface));

            jclass @class = nativeInterface.FindClass(jniEnv, "java/lang/Thread");

            if (@class == jclass.Null)
            {
                throw new Exception("ERROR: JNI: Cannot find %s with FindClass.");
            }

            nativeInterface.ExceptionClear(jniEnv);

            jmethodID method = nativeInterface.GetMethodID(jniEnv, @class, "<init>", "()V");

            if (method == jmethodID.Null)
            {
                throw new Exception("Cannot find Thread constructor method.");
            }

            nativeInterface.ExceptionClear(jniEnv);
            jthread result = (jthread)nativeInterface.NewObject(jniEnv, @class, method);

            if (result == jthread.Null)
            {
                throw new Exception("Cannot create new Thread object");
            }

            nativeInterface.ExceptionClear(jniEnv);
            return(result);
        }
示例#5
0
        public void GetFuncDesc(int index, out IntPtr ppFuncDesc)
        {
            // Fail BEFORE allocating the handle to avoid leaks. If the real COM object fails in this method
            // and doesn't return the handle or clean it up itself there's not much we can do to avoid the leak.
            _faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_GetFuncDesc);

            ppFuncDesc = _memoryHelper.AllocateHandle(Marshal.SizeOf <FUNCDESC>());

            _memoryHelper.EnterSubAllocationScope(ppFuncDesc);
            FUNCDESC funcDesc = new FUNCDESC();

            funcDesc.lprgelemdescParam = _memoryHelper.AllocateHandle(_definedFunctions[index].parameters.Length * Marshal.SizeOf <ELEMDESC>());
            funcDesc.cParams           = (short)_definedFunctions[index].parameters.Length;

            for (int i = 0; i < _definedFunctions[index].parameters.Length; i++)
            {
                ELEMDESC elemDesc = new ELEMDESC();
                elemDesc.tdesc = _definedFunctions[index].parameters[i].CreateTypeDesc(
                    new IntPtr(index * s_HREF_FUNCSPARAM_OFFSET_PERFUNC + i + s_HREF_FUNCSPARAM_OFFSET), _memoryHelper);

                Marshal.StructureToPtr(
                    elemDesc,
                    new IntPtr(funcDesc.lprgelemdescParam.ToInt64() + i * Marshal.SizeOf <ELEMDESC>()),
                    false);
            }

            funcDesc.elemdescFunc.tdesc = _definedFunctions[index].returnType.CreateTypeDesc(
                new IntPtr(index + s_HREF_FUNCSRET_OFFSET), _memoryHelper);
            _memoryHelper.ExitSubAllocationScope();

            Marshal.StructureToPtr(funcDesc, ppFuncDesc, false);
        }
示例#6
0
 public static T PtrToStructure <T>(IntPtr ptr)
 {
     return(SystemMarshal.PtrToStructure <T>(ptr));
 }
示例#7
0
        /// <summary>Opens the device for sending direct commands</summary>
        /// <param name="devicePath">Device path</param>
        public Device(string devicePath)
        {
            PlatformId  = DetectOS.GetRealPlatformID();
            Timeout     = 15;
            Error       = false;
            IsRemovable = false;
            _devicePath = devicePath;

            if (devicePath.StartsWith("dic://", StringComparison.OrdinalIgnoreCase) ||
                devicePath.StartsWith("aaru://", StringComparison.OrdinalIgnoreCase))
            {
                devicePath =
                    devicePath.Substring(devicePath.StartsWith("dic://", StringComparison.OrdinalIgnoreCase) ? 6 : 7);

                string[] pieces = devicePath.Split('/');
                string   host   = pieces[0];
                devicePath = devicePath.Substring(host.Length);

                _remote = new Remote.Remote(host);

                if (devicePath.StartsWith('/'))
                {
                    devicePath = devicePath.Substring(1);
                }

                Error     = !_remote.Open(devicePath, out int errno);
                LastError = errno;
            }
            else
            {
                switch (PlatformId)
                {
                case PlatformID.Win32NT:
                {
                    FileHandle = Extern.CreateFile(devicePath, FileAccess.GenericRead | FileAccess.GenericWrite,
                                                   FileShare.Read | FileShare.Write, IntPtr.Zero,
                                                   FileMode.OpenExisting, FileAttributes.Normal, IntPtr.Zero);

                    if (((SafeFileHandle)FileHandle).IsInvalid)
                    {
                        Error     = true;
                        LastError = Marshal.GetLastWin32Error();
                    }

                    break;
                }

                case PlatformID.Linux:
                {
                    FileHandle =
                        Linux.Extern.open(devicePath,
                                          FileFlags.ReadWrite | FileFlags.NonBlocking | FileFlags.CreateNew);

                    if ((int)FileHandle < 0)
                    {
                        LastError = Marshal.GetLastWin32Error();

                        if (LastError == 13 ||
                            LastError == 30)    // EACCES or EROFS
                        {
                            FileHandle = Linux.Extern.open(devicePath, FileFlags.Readonly | FileFlags.NonBlocking);

                            if ((int)FileHandle < 0)
                            {
                                Error     = true;
                                LastError = Marshal.GetLastWin32Error();
                            }
                        }
                        else
                        {
                            Error = true;
                        }

                        LastError = Marshal.GetLastWin32Error();
                    }

                    break;
                }

                case PlatformID.FreeBSD:
                {
                    FileHandle = FreeBSD.Extern.cam_open_device(devicePath, FreeBSD.FileFlags.ReadWrite);

                    if (((IntPtr)FileHandle).ToInt64() == 0)
                    {
                        Error     = true;
                        LastError = Marshal.GetLastWin32Error();
                    }

                    var camDevice = (CamDevice)Marshal.PtrToStructure((IntPtr)FileHandle, typeof(CamDevice));

                    if (StringHandlers.CToString(camDevice.SimName) == "ata")
                    {
                        throw new
                              DeviceException("Parallel ATA devices are not supported on FreeBSD due to upstream bug #224250.");
                    }

                    break;
                }

                default: throw new DeviceException($"Platform {PlatformId} not yet supported.");
                }
            }

            if (Error)
            {
                throw new DeviceException(LastError);
            }

            // Seems ioctl(2) does not allow the atomicity needed
            if (_remote is null)
            {
                if (PlatformId == PlatformID.Linux)
                {
                    _readMultipleBlockCannotSetBlockCount = true;
                }
            }
            else if (_remote.ServerOperatingSystem == "Linux")
            {
                _readMultipleBlockCannotSetBlockCount = true;
            }

            Type     = DeviceType.Unknown;
            ScsiType = PeripheralDeviceTypes.UnknownDevice;

            byte[] ataBuf;
            byte[] inqBuf = null;

            if (Error)
            {
                throw new DeviceException(LastError);
            }

            bool scsiSense = true;

            if (_remote is null)
            {
                // Windows is answering SCSI INQUIRY for all device types so it needs to be detected first
                switch (PlatformId)
                {
                case PlatformID.Win32NT:
                    var query = new StoragePropertyQuery();
                    query.PropertyId           = StoragePropertyId.Device;
                    query.QueryType            = StorageQueryType.Standard;
                    query.AdditionalParameters = new byte[1];

                    IntPtr descriptorPtr = Marshal.AllocHGlobal(1000);
                    byte[] descriptorB   = new byte[1000];

                    uint returned = 0;
                    int  error    = 0;

                    bool hasError = !Extern.DeviceIoControlStorageQuery((SafeFileHandle)FileHandle,
                                                                        WindowsIoctl.IoctlStorageQueryProperty,
                                                                        ref query, (uint)Marshal.SizeOf(query),
                                                                        descriptorPtr, 1000, ref returned,
                                                                        IntPtr.Zero);

                    if (hasError)
                    {
                        error = Marshal.GetLastWin32Error();
                    }

                    Marshal.Copy(descriptorPtr, descriptorB, 0, 1000);

                    if (!hasError &&
                        error == 0)
                    {
                        var descriptor = new StorageDeviceDescriptor
                        {
                            Version               = BitConverter.ToUInt32(descriptorB, 0),
                            Size                  = BitConverter.ToUInt32(descriptorB, 4),
                            DeviceType            = descriptorB[8],
                            DeviceTypeModifier    = descriptorB[9],
                            RemovableMedia        = descriptorB[10] > 0,
                            CommandQueueing       = descriptorB[11] > 0,
                            VendorIdOffset        = BitConverter.ToInt32(descriptorB, 12),
                            ProductIdOffset       = BitConverter.ToInt32(descriptorB, 16),
                            ProductRevisionOffset = BitConverter.ToInt32(descriptorB, 20),
                            SerialNumberOffset    = BitConverter.ToInt32(descriptorB, 24),
                            BusType               = (StorageBusType)BitConverter.ToUInt32(descriptorB, 28),
                            RawPropertiesLength   = BitConverter.ToUInt32(descriptorB, 32)
                        };

                        descriptor.RawDeviceProperties = new byte[descriptor.RawPropertiesLength];

                        Array.Copy(descriptorB, 36, descriptor.RawDeviceProperties, 0,
                                   descriptor.RawPropertiesLength);

                        switch (descriptor.BusType)
                        {
                        case StorageBusType.SCSI:
                        case StorageBusType.SSA:
                        case StorageBusType.Fibre:
                        case StorageBusType.iSCSI:
                        case StorageBusType.SAS:
                            Type = DeviceType.SCSI;

                            break;

                        case StorageBusType.FireWire:
                            IsFireWire = true;
                            Type       = DeviceType.SCSI;

                            break;

                        case StorageBusType.USB:
                            IsUsb = true;
                            Type  = DeviceType.SCSI;

                            break;

                        case StorageBusType.ATAPI:
                            Type = DeviceType.ATAPI;

                            break;

                        case StorageBusType.ATA:
                        case StorageBusType.SATA:
                            Type = DeviceType.ATA;

                            break;

                        case StorageBusType.MultiMediaCard:
                            Type = DeviceType.MMC;

                            break;

                        case StorageBusType.SecureDigital:
                            Type = DeviceType.SecureDigital;

                            break;

                        case StorageBusType.NVMe:
                            Type = DeviceType.NVMe;

                            break;
                        }

                        switch (Type)
                        {
                        case DeviceType.SCSI:
                        case DeviceType.ATAPI:
                            scsiSense = ScsiInquiry(out inqBuf, out _);

                            break;

                        case DeviceType.ATA:
                            bool atapiSense = AtapiIdentify(out ataBuf, out _);

                            if (!atapiSense)
                            {
                                Type = DeviceType.ATAPI;
                                Identify.IdentifyDevice?ataid = Identify.Decode(ataBuf);

                                if (ataid.HasValue)
                                {
                                    scsiSense = ScsiInquiry(out inqBuf, out _);
                                }
                            }
                            else
                            {
                                Manufacturer = "ATA";
                            }

                            break;
                        }
                    }

                    Marshal.FreeHGlobal(descriptorPtr);

                    if (Windows.Command.IsSdhci((SafeFileHandle)FileHandle))
                    {
                        byte[] sdBuffer = new byte[16];

                        LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle, MmcCommands.SendCsd,
                                                                   false, false,
                                                                   MmcFlags.ResponseSpiR2 | MmcFlags.ResponseR2 |
                                                                   MmcFlags.CommandAc, 0, 16, 1, ref sdBuffer,
                                                                   out _, out _, out bool sense);

                        if (!sense)
                        {
                            _cachedCsd = new byte[16];
                            Array.Copy(sdBuffer, 0, _cachedCsd, 0, 16);
                        }

                        sdBuffer = new byte[16];

                        LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle, MmcCommands.SendCid,
                                                                   false, false,
                                                                   MmcFlags.ResponseSpiR2 | MmcFlags.ResponseR2 |
                                                                   MmcFlags.CommandAc, 0, 16, 1, ref sdBuffer,
                                                                   out _, out _, out sense);

                        if (!sense)
                        {
                            _cachedCid = new byte[16];
                            Array.Copy(sdBuffer, 0, _cachedCid, 0, 16);
                        }

                        sdBuffer = new byte[8];

                        LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle,
                                                                   (MmcCommands)SecureDigitalCommands.SendScr,
                                                                   false, true,
                                                                   MmcFlags.ResponseSpiR1 | MmcFlags.ResponseR1 |
                                                                   MmcFlags.CommandAdtc, 0, 8, 1, ref sdBuffer,
                                                                   out _, out _, out sense);

                        if (!sense)
                        {
                            _cachedScr = new byte[8];
                            Array.Copy(sdBuffer, 0, _cachedScr, 0, 8);
                        }

                        sdBuffer = new byte[4];

                        LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle,
                                                                   _cachedScr != null
                                                                           ? (MmcCommands)SecureDigitalCommands.
                                                                   SendOperatingCondition
                                                                           : MmcCommands.SendOpCond, false, true,
                                                                   MmcFlags.ResponseSpiR3 | MmcFlags.ResponseR3 |
                                                                   MmcFlags.CommandBcr, 0, 4, 1, ref sdBuffer,
                                                                   out _, out _, out sense);

                        if (!sense)
                        {
                            _cachedScr = new byte[4];
                            Array.Copy(sdBuffer, 0, _cachedScr, 0, 4);
                        }
                    }

                    break;

                case PlatformID.Linux:
                    if (devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/st", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/sg", StringComparison.Ordinal))
                    {
                        scsiSense = ScsiInquiry(out inqBuf, out _);
                    }

                    // MultiMediaCard and SecureDigital go here
                    else if (devicePath.StartsWith("/dev/mmcblk", StringComparison.Ordinal))
                    {
                        string devPath = devicePath.Substring(5);

                        if (File.Exists("/sys/block/" + devPath + "/device/csd"))
                        {
                            int len = ConvertFromFileHexAscii("/sys/block/" + devPath + "/device/csd",
                                                              out _cachedCsd);

                            if (len == 0)
                            {
                                _cachedCsd = null;
                            }
                        }

                        if (File.Exists("/sys/block/" + devPath + "/device/cid"))
                        {
                            int len = ConvertFromFileHexAscii("/sys/block/" + devPath + "/device/cid",
                                                              out _cachedCid);

                            if (len == 0)
                            {
                                _cachedCid = null;
                            }
                        }

                        if (File.Exists("/sys/block/" + devPath + "/device/scr"))
                        {
                            int len = ConvertFromFileHexAscii("/sys/block/" + devPath + "/device/scr",
                                                              out _cachedScr);

                            if (len == 0)
                            {
                                _cachedScr = null;
                            }
                        }

                        if (File.Exists("/sys/block/" + devPath + "/device/ocr"))
                        {
                            int len = ConvertFromFileHexAscii("/sys/block/" + devPath + "/device/ocr",
                                                              out _cachedOcr);

                            if (len == 0)
                            {
                                _cachedOcr = null;
                            }
                        }
                    }

                    break;

                default:
                    scsiSense = ScsiInquiry(out inqBuf, out _);

                    break;
                }
            }
            else
            {
                Type = _remote.GetDeviceType();

                switch (Type)
                {
                case DeviceType.ATAPI:
                case DeviceType.SCSI:
                    scsiSense = ScsiInquiry(out inqBuf, out _);

                    break;

                case DeviceType.SecureDigital:
                case DeviceType.MMC:
                    if (!_remote.GetSdhciRegisters(out _cachedCsd, out _cachedCid, out _cachedOcr, out _cachedScr))
                    {
                        Type     = DeviceType.SCSI;
                        ScsiType = PeripheralDeviceTypes.DirectAccess;
                    }

                    break;
                }
            }

            #region SecureDigital / MultiMediaCard
            if (_cachedCid != null)
            {
                ScsiType    = PeripheralDeviceTypes.DirectAccess;
                IsRemovable = false;

                if (_cachedScr != null)
                {
                    Type = DeviceType.SecureDigital;
                    CID decoded = Decoders.SecureDigital.Decoders.DecodeCID(_cachedCid);
                    Manufacturer = VendorString.Prettify(decoded.Manufacturer);
                    Model        = decoded.ProductName;

                    FirmwareRevision =
                        $"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";

                    Serial = $"{decoded.ProductSerialNumber}";
                }
                else
                {
                    Type = DeviceType.MMC;
                    Decoders.MMC.CID decoded = Decoders.MMC.Decoders.DecodeCID(_cachedCid);
                    Manufacturer = Decoders.MMC.VendorString.Prettify(decoded.Manufacturer);
                    Model        = decoded.ProductName;

                    FirmwareRevision =
                        $"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";

                    Serial = $"{decoded.ProductSerialNumber}";
                }

                return;
            }
            #endregion SecureDigital / MultiMediaCard

            #region USB
            if (_remote is null)
            {
                switch (PlatformId)
                {
                case PlatformID.Linux:
                    if (devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/st", StringComparison.Ordinal))
                    {
                        string devPath = devicePath.Substring(5);

                        if (Directory.Exists("/sys/block/" + devPath))
                        {
                            string resolvedLink = Linux.Command.ReadLink("/sys/block/" + devPath);

                            if (!string.IsNullOrEmpty(resolvedLink))
                            {
                                resolvedLink = "/sys" + resolvedLink.Substring(2);

                                while (resolvedLink.Contains("usb"))
                                {
                                    resolvedLink = Path.GetDirectoryName(resolvedLink);

                                    if (!File.Exists(resolvedLink + "/descriptors") ||
                                        !File.Exists(resolvedLink + "/idProduct") ||
                                        !File.Exists(resolvedLink + "/idVendor"))
                                    {
                                        continue;
                                    }

                                    var usbFs = new FileStream(resolvedLink + "/descriptors",
                                                               System.IO.FileMode.Open, System.IO.FileAccess.Read);

                                    byte[] usbBuf   = new byte[65536];
                                    int    usbCount = usbFs.Read(usbBuf, 0, 65536);
                                    UsbDescriptors = new byte[usbCount];
                                    Array.Copy(usbBuf, 0, UsbDescriptors, 0, usbCount);
                                    usbFs.Close();

                                    var    usbSr   = new StreamReader(resolvedLink + "/idProduct");
                                    string usbTemp = usbSr.ReadToEnd();

                                    ushort.TryParse(usbTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
                                                    out _usbProduct);

                                    usbSr.Close();

                                    usbSr   = new StreamReader(resolvedLink + "/idVendor");
                                    usbTemp = usbSr.ReadToEnd();

                                    ushort.TryParse(usbTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
                                                    out _usbVendor);

                                    usbSr.Close();

                                    if (File.Exists(resolvedLink + "/manufacturer"))
                                    {
                                        usbSr = new StreamReader(resolvedLink + "/manufacturer");
                                        UsbManufacturerString = usbSr.ReadToEnd().Trim();
                                        usbSr.Close();
                                    }

                                    if (File.Exists(resolvedLink + "/product"))
                                    {
                                        usbSr            = new StreamReader(resolvedLink + "/product");
                                        UsbProductString = usbSr.ReadToEnd().Trim();
                                        usbSr.Close();
                                    }

                                    if (File.Exists(resolvedLink + "/serial"))
                                    {
                                        usbSr           = new StreamReader(resolvedLink + "/serial");
                                        UsbSerialString = usbSr.ReadToEnd().Trim();
                                        usbSr.Close();
                                    }

                                    IsUsb = true;

                                    break;
                                }
                            }
                        }
                    }

                    break;

                case PlatformID.Win32NT:
                    Usb.UsbDevice usbDevice = null;

                    // I have to search for USB disks, floppies and CD-ROMs as separate device types
                    foreach (string devGuid in new[]
                    {
                        Usb.GuidDevinterfaceFloppy, Usb.GuidDevinterfaceCdrom, Usb.GuidDevinterfaceDisk,
                        Usb.GuidDevinterfaceTape
                    })
                    {
                        usbDevice = Usb.FindDrivePath(devicePath, devGuid);

                        if (usbDevice != null)
                        {
                            break;
                        }
                    }

                    if (usbDevice != null)
                    {
                        UsbDescriptors        = usbDevice.BinaryDescriptors;
                        _usbVendor            = (ushort)usbDevice.DeviceDescriptor.idVendor;
                        _usbProduct           = (ushort)usbDevice.DeviceDescriptor.idProduct;
                        UsbManufacturerString = usbDevice.Manufacturer;
                        UsbProductString      = usbDevice.Product;

                        UsbSerialString =
                            usbDevice.
                            SerialNumber;         // This is incorrect filled by Windows with SCSI/ATA serial number
                    }

                    break;

                default:
                    IsUsb = false;

                    break;
                }
            }
            else
            {
                if (_remote.GetUsbData(out byte[] remoteUsbDescriptors, out ushort remoteUsbVendor,
                                       out ushort remoteUsbProduct, out string remoteUsbManufacturer,
                                       out string remoteUsbProductString, out string remoteUsbSerial))
                {
                    IsUsb                 = true;
                    UsbDescriptors        = remoteUsbDescriptors;
                    _usbVendor            = remoteUsbVendor;
                    _usbProduct           = remoteUsbProduct;
                    UsbManufacturerString = remoteUsbManufacturer;
                    UsbProductString      = remoteUsbProductString;
                    UsbSerialString       = remoteUsbSerial;
                }
            }
            #endregion USB

            #region FireWire
            if (!(_remote is null))
            {
                if (_remote.GetFireWireData(out _firewireVendor, out _firewireModel, out _firewireGuid,
                                            out string remoteFireWireVendorName, out string remoteFireWireModelName))
                {
                    IsFireWire         = true;
                    FireWireVendorName = remoteFireWireVendorName;
                    FireWireModelName  = remoteFireWireModelName;
                }
            }
示例#8
0
        public static int LaunchDebugTargets(this IVsDebugger2 debugger, params DebugTargetInfo[] targets)
        {
            VsDebugTargetInfo2[] vstargets = new VsDebugTargetInfo2[targets.Length];

            try
            {
                for (int i = 0; i < targets.Length; i++)
                {
                    vstargets[i].bstrArg           = targets[i].Arguments;
                    vstargets[i].bstrCurDir        = targets[i].CurrentDirectory;
                    vstargets[i].bstrEnv           = GetEnvironmentString(targets[i].Environment);
                    vstargets[i].bstrExe           = targets[i].Executable;
                    vstargets[i].bstrOptions       = targets[i].Options;
                    vstargets[i].bstrPortName      = targets[i].PortName;
                    vstargets[i].bstrRemoteMachine = targets[i].RemoteMachine;
                    vstargets[i].cbSize            = (uint)Marshal.SizeOf(typeof(VsDebugTargetInfo2));
                    vstargets[i].dlo                   = (uint)targets[i].LaunchOperation;
                    vstargets[i].dwProcessId           = targets[i].ProcessId;
                    vstargets[i].dwReserved            = 0;
                    vstargets[i].fSendToOutputWindow   = targets[i].SendToOutputWindow ? 1 : 0;
                    vstargets[i].guidLaunchDebugEngine = Guid.Empty;
                    vstargets[i].guidPortSupplier      = targets[i].PortSupplier;
                    vstargets[i].guidProcessLanguage   = targets[i].ProcessLanguage;
                    //vstargets[i].hStdError = targets[i].StdError;
                    //vstargets[i].hStdInput = targets[i].StdInput;
                    //vstargets[i].hStdOutput = targets[i].StdOutput;
                    vstargets[i].LaunchFlags = (uint)targets[i].LaunchFlags;
                    vstargets[i].pUnknown    = null;

                    vstargets[i].dwDebugEngineCount = (uint)targets[i].DebugEngines.Length;
                    vstargets[i].pDebugEngines      = Marshal.AllocHGlobal(targets[i].DebugEngines.Length * Marshal.SizeOf(typeof(Guid)));
                    for (int j = 0; j < targets[i].DebugEngines.Length; j++)
                    {
                        Marshal.StructureToPtr(targets[i].DebugEngines[j], new IntPtr(vstargets[i].pDebugEngines.ToInt64() + j * Marshal.SizeOf(typeof(Guid))), false);
                    }
                }

                return(debugger.LaunchDebugTargets(vstargets));
            }
            finally
            {
                for (int i = 0; i < vstargets.Length; i++)
                {
                    if (vstargets[i].pDebugEngines != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(vstargets[i].pDebugEngines);
                    }
                }
            }
        }
示例#9
0
        /// <summary>
        /// Reads a specified number of bytes from the stream object into memory starting
        /// at the current seek pointer.
        /// </summary>
        /// <param name="pv">Upon return, contains the data read from the stream.</param>
        /// <param name="cb">The number of bytes to read from the stream object.</param>
        /// <param name="pcbRead">
        /// A pointer to a ULONG variable that receives the actual number of bytes read
        /// from the stream object.
        /// </param>

        public void Read(byte[] pv, int cb, IntPtr pcbRead)
        {
            Marshal.WriteInt64(pcbRead, (long)stream.Read(pv, 0, cb));
        }
示例#10
0
        /// <summary>
        /// Writes a specified number of bytes into the stream object starting at the
        /// current seek pointer.
        /// </summary>
        /// <param name="pv">The buffer to write this stream to.</param>
        /// <param name="cb">The number of bytes to write to the stream.</param>
        /// <param name="pcbWritten">
        /// Upon return, contains the actual number of bytes written to the stream object.
        /// If the caller sets this pointer to System.IntPtr.Zero, this method does not provide
        /// the actual number of bytes written.
        /// </param>

        public void Write(byte[] pv, int cb, IntPtr pcbWritten)
        {
            Marshal.WriteInt64(pcbWritten, 0L);
            stream.Write(pv, 0, cb);
            Marshal.WriteInt64(pcbWritten, (long)cb);
        }
示例#11
0
文件: semaphore.cs 项目: nsivov/mono
        private static OpenExistingResult OpenExistingWorker(
            string name,
#if !FEATURE_PAL && !FEATURE_NETCORE
            SemaphoreRights rights,
#endif
            out Semaphore result)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (name.Length == 0)
            {
                throw new ArgumentException(SR.GetString(SR.InvalidNullEmptyArgument, "name"), "name");
            }
            if (null != name && MAX_PATH < name.Length)
            {
                throw new ArgumentException(SR.GetString(SR.Argument_WaitHandleNameTooLong));
            }

            result = null;
#if MOBILE
            throw new NotSupportedException();
#else
#if MONO
            int errorCode;
            var myHandle = new SafeWaitHandle(OpenSemaphore_internal(name, rights, out errorCode), true);
#else
            //Pass false to OpenSemaphore to prevent inheritedHandles
#if FEATURE_PAL || FEATURE_NETCORE
            const int SYNCHRONIZE            = 0x00100000;
            const int SEMAPHORE_MODIFY_STATE = 0x00000002;

            SafeWaitHandle myHandle = SafeNativeMethods.OpenSemaphore(SEMAPHORE_MODIFY_STATE | SYNCHRONIZE, false, name);
#else
            SafeWaitHandle myHandle = SafeNativeMethods.OpenSemaphore((int)rights, false, name);
#endif
#endif

            if (myHandle.IsInvalid)
            {
#if !MONO
                int errorCode = Marshal.GetLastWin32Error();
#endif

                if (NativeMethods.ERROR_FILE_NOT_FOUND == errorCode || NativeMethods.ERROR_INVALID_NAME == errorCode)
                {
                    return(OpenExistingResult.NameNotFound);
                }
                if (NativeMethods.ERROR_PATH_NOT_FOUND == errorCode)
                {
                    return(OpenExistingResult.PathNotFound);
                }
                if (null != name && 0 != name.Length && NativeMethods.ERROR_INVALID_HANDLE == errorCode)
                {
                    return(OpenExistingResult.NameInvalid);
                }
                //this is for passed through NativeMethods Errors
#if MONO
                InternalResources.WinIOError(errorCode, "");
#else
                InternalResources.WinIOError();
#endif
            }
            result = new Semaphore(myHandle);
            return(OpenExistingResult.Success);
#endif
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="grfCreateDoc"></param>
        /// <param name="pszMkDocument"></param>
        /// <param name="pszPhysicalView"></param>
        /// <param name="pvHier"></param>
        /// <param name="itemid"></param>
        /// <param name="punkDocDataExisting"></param>
        /// <param name="ppunkDocView"></param>
        /// <param name="ppunkDocData"></param>
        /// <param name="pbstrEditorCaption"></param>
        /// <param name="pguidCmdUI"></param>
        /// <param name="pgrfCDW"></param>
        /// <returns></returns>
        public virtual int CreateEditorInstance(
            uint createEditorFlags,
            string documentMoniker,
            string physicalView,
            IVsHierarchy hierarchy,
            uint itemid,
            IntPtr docDataExisting,
            out IntPtr docView,
            out IntPtr docData,
            out string editorCaption,
            out Guid commandUIGuid,
            out int createDocumentWindowFlags)
        {
            // Initialize output parameters
            docView                   = IntPtr.Zero;
            docData                   = IntPtr.Zero;
            commandUIGuid             = Guid.Empty;
            createDocumentWindowFlags = 0;
            editorCaption             = null;

            // Validate inputs
            if ((createEditorFlags & (uint)(VSConstants.CEF.OpenFile | VSConstants.CEF.Silent)) == 0)
            {
                return(VSConstants.E_INVALIDARG);
            }

            if (docDataExisting != IntPtr.Zero && _promptEncodingOnLoad)
            {
                return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
            }

            // Get a text buffer
            IVsTextLines textLines = GetTextBuffer(docDataExisting, documentMoniker);

            // Assign docData IntPtr to either existing docData or the new text buffer
            if (docDataExisting != IntPtr.Zero)
            {
                docData = docDataExisting;
                Marshal.AddRef(docData);
            }
            else
            {
                docData = Marshal.GetIUnknownForObject(textLines);
            }

            try
            {
                object docViewObject = CreateDocumentView(documentMoniker, physicalView, hierarchy, itemid, textLines, docDataExisting == IntPtr.Zero, out editorCaption, out commandUIGuid);
                docView = Marshal.GetIUnknownForObject(docViewObject);
            }
            finally
            {
                if (docView == IntPtr.Zero)
                {
                    if (docDataExisting != docData && docData != IntPtr.Zero)
                    {
                        // Cleanup the instance of the docData that we have addref'ed
                        Marshal.Release(docData);
                        docData = IntPtr.Zero;
                    }
                }
            }
            return(VSConstants.S_OK);
        }
示例#13
0
        internal static DeviceInfo[] GetList()
        {
            List <string> deviceIDs = new List <string>();

            try
            {
                var mgmtObjSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

                ManagementObjectCollection objCol = mgmtObjSearcher.Get();

                deviceIDs.AddRange(from ManagementObject drive in objCol select(string) drive["DeviceID"]);

                mgmtObjSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_TapeDrive");
                objCol          = mgmtObjSearcher.Get();

                deviceIDs.AddRange(from ManagementObject drive in objCol select(string) drive["DeviceID"]);

                mgmtObjSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_CDROMDrive");
                objCol          = mgmtObjSearcher.Get();

                deviceIDs.AddRange(from ManagementObject drive in objCol select(string) drive["Drive"]);
            }
            catch (Exception)
            {
            #if DEBUG
                throw;
            #else
                return(null);
            #endif
            }

            List <DeviceInfo> devList = new List <DeviceInfo>();

            foreach (string devId in deviceIDs)
            {
                if (devId is null)
                {
                    continue;
                }

                string physId = devId;

                // TODO: This can be done better
                if (devId.Length == 2 &&
                    devId[1] == ':')
                {
                    physId = "\\\\?\\" + devId;
                }

                SafeFileHandle fd = Extern.CreateFile(physId, 0, FileShare.Read | FileShare.Write, IntPtr.Zero,
                                                      FileMode.OpenExisting, 0, IntPtr.Zero);

                if (fd.IsInvalid)
                {
                    continue;
                }

                var query = new StoragePropertyQuery
                {
                    PropertyId           = StoragePropertyId.Device,
                    QueryType            = StorageQueryType.Standard,
                    AdditionalParameters = new byte[1]
                };

                //StorageDeviceDescriptor descriptor = new StorageDeviceDescriptor();
                //descriptor.RawDeviceProperties = new byte[16384];

                IntPtr descriptorPtr = Marshal.AllocHGlobal(1000);
                byte[] descriptorB   = new byte[1000];

                uint returned = 0;
                int  error    = 0;

                bool hasError = !Extern.DeviceIoControlStorageQuery(fd, WindowsIoctl.IoctlStorageQueryProperty,
                                                                    ref query, (uint)Marshal.SizeOf(query),
                                                                    descriptorPtr, 1000, ref returned, IntPtr.Zero);

                if (hasError)
                {
                    error = Marshal.GetLastWin32Error();
                }

                Marshal.Copy(descriptorPtr, descriptorB, 0, 1000);

                if (hasError && error != 0)
                {
                    continue;
                }

                var descriptor = new StorageDeviceDescriptor
                {
                    Version               = BitConverter.ToUInt32(descriptorB, 0),
                    Size                  = BitConverter.ToUInt32(descriptorB, 4),
                    DeviceType            = descriptorB[8],
                    DeviceTypeModifier    = descriptorB[9],
                    RemovableMedia        = BitConverter.ToBoolean(descriptorB, 10),
                    CommandQueueing       = BitConverter.ToBoolean(descriptorB, 11),
                    VendorIdOffset        = BitConverter.ToInt32(descriptorB, 12),
                    ProductIdOffset       = BitConverter.ToInt32(descriptorB, 16),
                    ProductRevisionOffset = BitConverter.ToInt32(descriptorB, 20),
                    SerialNumberOffset    = BitConverter.ToInt32(descriptorB, 24),
                    BusType               = (StorageBusType)BitConverter.ToUInt32(descriptorB, 28),
                    RawPropertiesLength   = BitConverter.ToUInt32(descriptorB, 32)
                };

                var info = new DeviceInfo
                {
                    Path = physId,
                    Bus  = descriptor.BusType.ToString()
                };

                if (descriptor.VendorIdOffset > 0)
                {
                    info.Vendor =
                        StringHandlers.CToString(descriptorB, Encoding.ASCII, start: descriptor.VendorIdOffset);
                }

                if (descriptor.ProductIdOffset > 0)
                {
                    info.Model =
                        StringHandlers.CToString(descriptorB, Encoding.ASCII, start: descriptor.ProductIdOffset);
                }

                // TODO: Get serial number of SCSI and USB devices, probably also FireWire (untested)
                if (descriptor.SerialNumberOffset > 0)
                {
                    info.Serial =
                        StringHandlers.CToString(descriptorB, Encoding.ASCII, start: descriptor.SerialNumberOffset);

                    // fix any serial numbers that are returned as hex-strings
                    if (Array.TrueForAll(info.Serial.ToCharArray(), c => "0123456789abcdef".IndexOf(c) >= 0) &&
                        info.Serial.Length == 40)
                    {
                        info.Serial = HexStringToString(info.Serial).Trim();
                    }
                }

                if (string.IsNullOrEmpty(info.Vendor) ||
                    info.Vendor == "ATA")
                {
                    string[] pieces = info.Model?.Split(' ');

                    if (pieces?.Length > 1)
                    {
                        info.Vendor = pieces[0];
                        info.Model  = info.Model.Substring(pieces[0].Length + 1);
                    }
                }

                switch (descriptor.BusType)
                {
                case StorageBusType.SCSI:
                case StorageBusType.ATAPI:
                case StorageBusType.ATA:
                case StorageBusType.FireWire:
                case StorageBusType.SSA:
                case StorageBusType.Fibre:
                case StorageBusType.USB:
                case StorageBusType.iSCSI:
                case StorageBusType.SAS:
                case StorageBusType.SATA:
                case StorageBusType.SecureDigital:
                case StorageBusType.MultiMediaCard:
                    info.Supported = true;

                    break;
                }

                Marshal.FreeHGlobal(descriptorPtr);
                devList.Add(info);
            }

            DeviceInfo[] devices = devList.ToArray();

            return(devices);
        }
示例#14
0
        /// <summary>
        /// Strips type library number from a type library path (for example, "ref.dll\2" becomes "ref.dll")
        /// </summary>
        /// <param name="typeLibPath">type library path with possible typelib number appended to it</param>
        /// <returns>proper file path to the type library</returns>
        internal static string StripTypeLibNumberFromPath(string typeLibPath, FileExists fileExists)
        {
            bool lastChance = false;

            if (typeLibPath != null && typeLibPath.Length > 0)
            {
                if (!fileExists(typeLibPath))
                {
                    // Strip the type library number
                    int lastSlash = typeLibPath.LastIndexOf('\\');

                    if (lastSlash != -1)
                    {
                        bool allNumbers = true;

                        for (int i = lastSlash + 1; i < typeLibPath.Length; i++)
                        {
                            if (!Char.IsDigit(typeLibPath[i]))
                            {
                                allNumbers = false;
                                break;
                            }
                        }

                        // If we had all numbers past the last slash then we're OK to strip
                        // the type library number
                        if (allNumbers)
                        {
                            typeLibPath = typeLibPath.Substring(0, lastSlash);
                            if (!fileExists(typeLibPath))
                            {
                                lastChance = true;
                            }
                        }
                        else
                        {
                            lastChance = true;
                        }
                    }
                    else
                    {
                        lastChance = true;
                    }
                }
            }

            // If we couldn't find the path directly, we'll use the same mechanism Windows uses to find
            // libraries.  LoadLibrary() will search all of the correct paths to find this module.  We can then
            // use GetModuleFileName() to determine the actual path from which the module was loaded.  This problem
            // was exposed in Vista where certain libraries are registered but are lacking paths in the registry,
            // so the old code would fail to find them on disk using the simplistic checks above.
            if (lastChance)
            {
                IntPtr libraryHandle = NativeMethodsShared.LoadLibrary(typeLibPath);
                if (IntPtr.Zero != libraryHandle)
                {
                    try
                    {
                        StringBuilder sb = new StringBuilder(NativeMethodsShared.MAX_PATH);
                        System.Runtime.InteropServices.HandleRef handleRef = new System.Runtime.InteropServices.HandleRef(sb, libraryHandle);
                        int len = NativeMethodsShared.GetModuleFileName(handleRef, sb, sb.Capacity);
                        if ((len != 0) &&
                            ((uint)Marshal.GetLastWin32Error() != NativeMethodsShared.ERROR_INSUFFICIENT_BUFFER))
                        {
                            typeLibPath = sb.ToString();
                        }
                        else
                        {
                            typeLibPath = "";
                        }
                    }
                    finally
                    {
                        NativeMethodsShared.FreeLibrary(libraryHandle);
                    }
                }
                else
                {
                    typeLibPath = "";
                }
            }

            return(typeLibPath);
        }
示例#15
0
 static CameraApi()
 {
     _totalBufferSize = TextureWidth * TextureHeight * (BitsPerPixel / 8);
     RawPixelBuffer   = Marshal.AllocHGlobal(_totalBufferSize);
     _rgbTexture      = new Texture(TextureWidth, TextureHeight, TextureFormat, EnableMipmap);
 }
        public bool TryGetValues(IntPtr cameraMetadataHandle,
                                 CameraMetadataTag tag, List <CameraMetadataValue> resultList)
        {
            IntPtr ndkMetadataHandle = IntPtr.Zero;

            ExternApi.ArImageMetadata_getNdkCameraMetadata(_nativeSession.SessionHandle,
                                                           cameraMetadataHandle, ref ndkMetadataHandle);

            resultList.Clear();
            NdkCameraMetadata entry  = new NdkCameraMetadata();
            NdkCameraStatus   status =
                ExternApi.ACameraMetadata_getConstEntry(ndkMetadataHandle, tag, ref entry);

            if (status != NdkCameraStatus.Ok)
            {
                ARDebug.LogErrorFormat(
                    "ACameraMetadata_getConstEntry error with native camera error code: {0}",
                    status);
                return(false);
            }

            if (entry.Count > _maximumTagCountForWarning && !_warningTags.Contains((int)tag))
            {
                Debug.LogWarningFormat(
                    "TryGetValues for tag {0} has {1} values. Accessing tags with a large " +
                    "number of values may impede performance.", tag, entry.Count);
                _warningTags.Add((int)tag);
            }

            for (int i = 0; i < entry.Count; i++)
            {
                switch (entry.Type)
                {
                case NdkCameraMetadataType.Byte:
                    sbyte byteValue = (sbyte)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <sbyte>(entry.Value, i),
                        typeof(sbyte));
                    resultList.Add(new CameraMetadataValue(byteValue));
                    break;

                case NdkCameraMetadataType.Int32:
                    int intValue = (int)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <int>(entry.Value, i),
                        typeof(int));
                    resultList.Add(new CameraMetadataValue(intValue));
                    break;

                case NdkCameraMetadataType.Float:
                    float floatValue = (float)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <float>(entry.Value, i),
                        typeof(float));
                    resultList.Add(new CameraMetadataValue(floatValue));
                    break;

                case NdkCameraMetadataType.Int64:
                    long longValue = (long)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <long>(entry.Value, i),
                        typeof(long));
                    resultList.Add(new CameraMetadataValue(longValue));
                    break;

                case NdkCameraMetadataType.Double:
                    double doubleValue = (double)Marshal.PtrToStructure(
                        MarshalingHelper.GetPtrToUnmanagedArrayElement <double>(entry.Value, i),
                        typeof(double));
                    resultList.Add(new CameraMetadataValue(doubleValue));
                    break;

                case NdkCameraMetadataType.Rational:
                    CameraMetadataRational rationalValue =
                        (CameraMetadataRational)Marshal.PtrToStructure(
                            MarshalingHelper
                            .GetPtrToUnmanagedArrayElement <CameraMetadataRational>(
                                entry.Value, i),
                            typeof(CameraMetadataRational));
                    resultList.Add(new CameraMetadataValue(rationalValue));
                    break;

                default:
                    return(false);
                }
            }

            return(true);
        }
示例#17
0
        internal static void WinIOError()
        {
            int errorCode = Marshal.GetLastWin32Error();

            WinIOError(errorCode, String.Empty);
        }
示例#18
0
        public override int DebugLaunch(uint aLaunch)
        {
            LogUtility.LogString("Cosmos.VS.Package.VSProjectConfig debugger launching");
            try {
                // Second param is ResetCache. Must be called one time. Dunno why.
                // Also dunno if this comment is still valid/needed:
                // On first call, reset the cache, following calls will use the cached values
                // Think we will change this to a dummy program when we get our debugger working
                // This is the program that gest launched after build
                var xDeployment = (DeploymentType)Enum.Parse(typeof(DeploymentType), GetConfigurationProperty(BuildProperties.DeploymentString, true));
                var xLaunch     = (LaunchType)Enum.Parse(typeof(LaunchType), GetConfigurationProperty(BuildProperties.LaunchString, false));

                string xOutputAsm  = ProjectMgr.GetOutputAssembly(ConfigName);
                string xOutputPath = Path.GetDirectoryName(xOutputAsm);
                string xIsoFile    = Path.ChangeExtension(xOutputAsm, ".iso");
                string xBinFile    = Path.ChangeExtension(xOutputAsm, ".bin");

                if (xDeployment == DeploymentType.ISO)
                {
                    IsoMaker.Generate(xBinFile, xIsoFile);
                }
                else if (xDeployment == DeploymentType.USB)
                {
                    Process.Start(Path.Combine(CosmosPaths.Tools, "Cosmos.Deploy.USB.exe"), "\"" + xBinFile + "\"");
                }
                else if (xDeployment == DeploymentType.PXE)
                {
                    string xPxePath = Path.Combine(CosmosPaths.Build, "PXE");
                    string xPxeIntf = GetConfigurationProperty(BuildProperties.PxeInterfaceString, false);
                    File.Copy(xBinFile, Path.Combine(xPxePath, "Cosmos.bin"), true);
                    Process.Start(Path.Combine(CosmosPaths.Tools, "Cosmos.Deploy.Pixie.exe"), xPxeIntf + " \"" + xPxePath + "\"");
                }
                else
                {
                    throw new Exception("Unknown deployment type.");
                }

                if (xLaunch == LaunchType.None)
                {
                    if (xDeployment == DeploymentType.ISO)
                    {
                        Process.Start(xOutputPath);
                    }
                }
                else
                {
                    // http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.shell.interop.vsdebugtargetinfo_members.aspx
                    var xInfo = new VsDebugTargetInfo();
                    xInfo.cbSize = (uint)Marshal.SizeOf(xInfo);

                    xInfo.dlo = DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;
                    xInfo.fSendStdoutToOutputWindow = 0; // App keeps its stdout
                    xInfo.grfLaunch         = aLaunch;   // Just pass through for now.
                    xInfo.bstrRemoteMachine = null;      // debug locally

                    var xValues = new NameValueCollection();
                    xValues.Add("ProjectFile", Path.Combine(ProjectMgr.ProjectFolder, ProjectMgr.ProjectFile));
                    xValues.Add("ISOFile", xIsoFile);
                    xValues.Add("BinFormat", GetConfigurationProperty("BinFormat", false));
                    foreach (var xName in BuildProperties.PropNames)
                    {
                        xValues.Add(xName, GetConfigurationProperty(xName, false));
                    }

                    xInfo.bstrExe = NameValueCollectionHelper.DumpToString(xValues);

                    // Select the debugger
                    xInfo.clsidCustom = new Guid("{FA1DA3A6-66FF-4c65-B077-E65F7164EF83}"); // Debug engine identifier.
                    // ??? This identifier doesn't seems to appear anywhere else in souce code.
                    xInfo.clsidPortSupplier = new Guid("{708C1ECA-FF48-11D2-904F-00C04FA302A1}");

                    VsShellUtilities.LaunchDebugger(ProjectMgr.Site, xInfo);
                }
            } catch (Exception ex) {
                LogUtility.LogException(ex, true);
                return(Marshal.GetHRForException(ex));
            }
            return(VSConstants.S_OK);
        }
        protected override void HandlePostExec(ref Guid commandGroup, uint commandId, uint executionOptions, IntPtr pvaIn, IntPtr pvaOut)
        {
            if (commandGroup == VsMenus.guidStandardCommandSet2K)
            {
                switch ((VSConstants.VSStd2KCmdID)commandId)
                {
                case VSConstants.VSStd2KCmdID.TYPECHAR:
                    //case VSConstants.VSStd2KCmdID.BACKSPACE:
                    //case VSConstants.VSStd2KCmdID.TAB:
                    //case VSConstants.VSStd2KCmdID.BACKTAB:
                    //case VSConstants.VSStd2KCmdID.DELETE:
                    char typedChar = Convert.ToChar(Marshal.GetObjectForNativeVariant(pvaIn));
                    switch (typedChar)
                    {
                    /* currently only implemented for $ references */
                    //case '@':
                    //case ':':
                    case '$':
                        //case '.':
                        SnapshotPoint currentPosition = TextView.Caret.Position.BufferPosition;
                        TextExtent    wordExtent      = TextStructureNavigator.GetExtentOfWord(currentPosition);
                        SnapshotSpan  wordSpan        = wordExtent.Span;
                        if (wordExtent.Span.Start >= currentPosition)
                        {
                            wordExtent = TextStructureNavigator.GetExtentOfWord(currentPosition - 1);
                            wordSpan   = wordExtent.Span;
                        }

                        if (wordSpan.End == currentPosition && wordSpan.Length <= 2)
                        {
                            string wordText = wordSpan.GetText();
                            switch (wordText)
                            {
                            case "@":
                            case "$":
                            {
                                ITrackingPoint triggerPoint = currentPosition.Snapshot.CreateTrackingPoint(currentPosition, PointTrackingMode.Positive);
                                base.Controller.TriggerCompletion(triggerPoint, CompletionInfoType.AutoListMemberInfo, IntellisenseInvocationType.IdentifierChar);
                            }
                            break;

                            case ".":
                            case "::":
                            {
                                ITrackingPoint triggerPoint = currentPosition.Snapshot.CreateTrackingPoint(currentPosition, PointTrackingMode.Positive);
                                base.Controller.TriggerCompletion(triggerPoint, CompletionInfoType.AutoListMemberInfo, IntellisenseInvocationType.ShowMemberList);
                            }
                            break;

                            default:
                                break;
                            }
                        }

                        break;

                    default:
                        break;
                    }
                    break;

                default:
                    break;
                }
            }

            base.HandlePostExec(ref commandGroup, commandId, executionOptions, pvaIn, pvaOut);
        }
示例#20
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                return;
            }

            if (!File.Exists(args[0]))
            {
                Console.WriteLine("Input file {0} does not exist.", args[0]);
                return;
            }

            var file = new BinaryReader(File.OpenRead(args[0]));

            var magic = new string(file.ReadChars(4));

            if (magic != "AIMG")
            {
                MessageBox.Show("Input file is not a valid Asspull IIIx image.");
                return;
            }
            //TODO: more checks?
            var depth      = file.ReadByte();
            var compressed = file.ReadByte() == 1;
            var width      = file.ReadMotoUInt16();
            var height     = file.ReadMotoUInt16();
            var stride     = file.ReadMotoUInt16();
            var palSize    = (depth == 8) ? 256 : 16;
            var dataSize   = file.ReadMotoUInt32();
            var palOffset  = file.ReadMotoUInt32();
            var dataOffset = file.ReadMotoUInt32();

            var bitmap  = new Bitmap(width, height, (depth == 8) ? PixelFormat.Format8bppIndexed : PixelFormat.Format4bppIndexed);
            var palette = bitmap.Palette;

            file.BaseStream.Seek(palOffset, SeekOrigin.Begin);
            for (var i = 0; i < palSize; i++)
            {
                var snes = file.ReadMotoUInt16();
                var r    = (snes >> 0) & 0x1F;
                var g    = (snes >> 5) & 0x1F;
                var b    = (snes >> 10) & 0x1F;
                palette.Entries[i] = Color.FromArgb((r << 3) + (r >> 2), (g << 3) + (g >> 2), (b << 3) + (b >> 2));
            }
            bitmap.Palette = palette;
            file.BaseStream.Seek(dataOffset, SeekOrigin.Begin);
            var screen = new byte[width * height];
            var pos    = 0;

            if (compressed)
            {
                while (file.BaseStream.Position < file.BaseStream.Length)
                {
                    var data = file.ReadByte();
                    if ((data & 0xC0) == 0xC0)
                    {
                        var rle      = data & 0x3F;
                        var original = data;
                        var from     = file.BaseStream.Position - 1;
                        data = file.ReadByte();
                        if (data == 0xC0 && rle == 0)
                        {
                            break;
                        }
                        for (; rle > 0; rle--)
                        {
                            screen[pos++] = data;
                        }
                    }
                    else
                    {
                        screen[pos++] = data;
                    }
                }
            }
            else
            {
                //TODO: check this, I only have compressed images right now.
                screen = file.ReadBytes((int)dataSize);
            }

            if (depth == 4)
            {
                for (var i = 0; i < width * height; i++)
                {
                    var a = (screen[i] >> 0) & 0x0F;
                    var b = (screen[i] >> 4) & 0x0F;
                    screen[i] = (byte)(b | (a << 4));
                }
            }

            var bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat);

            Marshal.Copy(screen, 0, bitmapData.Scan0, (width * height) / ((depth == 8) ? 1 : 2));

            var form = new Form()
            {
                ClientSize      = new Size(width, height),
                BackgroundImage = bitmap,
                Text            = Path.GetFileNameWithoutExtension(args[0])
            };

            Application.Run(form);
        }
        public virtual bool PreprocessCommand(ref Guid commandGroup, uint commandId, OLECMDEXECOPT executionOptions, IntPtr pvaIn, IntPtr pvaOut)
        {
            _isProcessingCommand = true;
            if (!IsCompletionActive)
            {
                return(false);
            }

            if (commandGroup == VsMenus.guidStandardCommandSet97)
            {
                if (commandId == (uint)VsCommands.Delete)
                {
                    return(false);
                }
            }
            else if (commandGroup == VsMenus.guidStandardCommandSet2K)
            {
                switch ((VsCommands2K)commandId)
                {
                case VsCommands2K.WORDPREV:
                case VsCommands2K.WORDPREV_EXT:
                case VsCommands2K.WORDNEXT:
                case VsCommands2K.WORDNEXT_EXT:
                case VsCommands2K.CANCEL:
                case VsCommands2K.BACKSPACE:
                case VsCommands2K.DELETE:
                case VsCommands2K.LEFT:
                case VsCommands2K.LEFT_EXT:
                case VsCommands2K.RIGHT:
                case VsCommands2K.RIGHT_EXT:
                case VsCommands2K.UP:
                case VsCommands2K.UP_EXT:
                case VsCommands2K.DOWN:
                case VsCommands2K.DOWN_EXT:
                case VsCommands2K.BOL:
                case VsCommands2K.BOL_EXT:
                case VsCommands2K.FIRSTCHAR:
                case VsCommands2K.FIRSTCHAR_EXT:
                case VsCommands2K.EOL:
                case VsCommands2K.EOL_EXT:
                case VsCommands2K.PAGEUP:
                case VsCommands2K.PAGEUP_EXT:
                case VsCommands2K.PAGEDN:
                case VsCommands2K.PAGEDN_EXT:
                case VsCommands2K.TOPLINE:
                case VsCommands2K.TOPLINE_EXT:
                case VsCommands2K.BOTTOMLINE:
                case VsCommands2K.BOTTOMLINE_EXT:
                case VsCommands2K.LEFT_EXT_COL:
                case VsCommands2K.RIGHT_EXT_COL:
                case IntellisenseCommandFilter.ECMD_INCREASEFILTER:
                case VsCommands2K.ECMD_DECREASEFILTER:
                case VsCommands2K.ECMD_LEFTCLICK:
                    return(false);

                case (VsCommands2K)95:
                case VsCommands2K.BACKTAB:
                case VsCommands2K.HOME:
                case VsCommands2K.HOME_EXT:
                case VsCommands2K.END:
                case VsCommands2K.END_EXT:
                case VsCommands2K.LASTCHAR:
                case VsCommands2K.LASTCHAR_EXT:
                    break;

                case VsCommands2K.TYPECHAR:
                    char c = Convert.ToChar(Marshal.GetObjectForNativeVariant(pvaIn));
                    if (IsCommitChar(c))
                    {
                        if (CompletionSession.SelectedCompletionSet.SelectionStatus.Completion == null)
                        {
                            DismissCompletion();
                        }
                        else
                        {
                            CompletionInfo.CommitChar = c;
                            return(CommitCompletion());
                        }
                    }

                    return(false);

                case VsCommands2K.RETURN:
                    CompletionInfo.CommitChar = '\n';
                    return(CommitCompletion());

                case VsCommands2K.TAB:
                case VsCommands2K.OPENLINEABOVE:
                    var selectionStatus = CompletionSession.SelectedCompletionSet.SelectionStatus;
                    CompletionSession.SelectedCompletionSet.SelectionStatus = new CompletionSelectionStatus(selectionStatus.Completion, true, selectionStatus.IsUnique);
                    CompletionInfo.CommitChar = (VsCommands2K)commandId == VsCommands2K.TAB ? (char?)'\t' : null;
                    return(CommitCompletion());

                case VsCommands2K.ToggleConsumeFirstCompletionMode:
                    return(false);
                }
            }

            return(false);
        }
示例#22
0
 public static int SizeOf <T>()
 {
     return(SystemMarshal.SizeOf <T>());
 }
示例#23
0
 private IntPtr Alloc()
 => Marshal.AllocCoTaskMem(BlockSize);
示例#24
0
        public unsafe Semaphore(int initialCount, int maximumCount, string name, out bool createdNew, SemaphoreSecurity semaphoreSecurity)
#endif
        {
            if (initialCount < 0)
            {
                throw new ArgumentOutOfRangeException("initialCount", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNumRequired));
            }

            if (maximumCount < 1)
            {
                throw new ArgumentOutOfRangeException("maximumCount", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNumRequired));
            }

            if (initialCount > maximumCount)
            {
                throw new ArgumentException(SR.GetString(SR.Argument_SemaphoreInitialMaximum));
            }

            if (null != name && MAX_PATH < name.Length)
            {
                throw new ArgumentException(SR.GetString(SR.Argument_WaitHandleNameTooLong));
            }
            SafeWaitHandle myHandle;

#if MONO
            int errorCode;
            myHandle = new SafeWaitHandle(CreateSemaphore_internal(initialCount, maximumCount, name, out errorCode), true);
#else
#if !FEATURE_PAL && !FEATURE_NETCORE
            // For ACL's, get the security descriptor from the SemaphoreSecurity.
            if (semaphoreSecurity != null)
            {
                NativeMethods.SECURITY_ATTRIBUTES secAttrs = null;
                secAttrs         = new NativeMethods.SECURITY_ATTRIBUTES();
                secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
                byte[] sd = semaphoreSecurity.GetSecurityDescriptorBinaryForm();
                fixed(byte *pSecDescriptor = sd)
                {
                    secAttrs.lpSecurityDescriptor = new SafeLocalMemHandle((IntPtr)pSecDescriptor, false);
                    myHandle = SafeNativeMethods.CreateSemaphore(secAttrs, initialCount, maximumCount, name);
                }
            }
            else
            {
#endif
            myHandle = SafeNativeMethods.CreateSemaphore(null, initialCount, maximumCount, name);
#if !FEATURE_PAL && !FEATURE_NETCORE
        }
#endif

            int errorCode = Marshal.GetLastWin32Error();
#endif
            if (myHandle.IsInvalid)
            {
                if (null != name && 0 != name.Length && NativeMethods.ERROR_INVALID_HANDLE == errorCode)
                {
                    throw new WaitHandleCannotBeOpenedException(SR.GetString(SR.WaitHandleCannotBeOpenedException_InvalidHandle, name));
                }

#if MONO
                InternalResources.WinIOError(errorCode, "");
#else
                InternalResources.WinIOError();
#endif
            }
            createdNew          = errorCode != NativeMethods.ERROR_ALREADY_EXISTS;
            this.SafeWaitHandle = myHandle;
        }
示例#25
0
        /// <summary>Gets a list of all known storage devices on FreeBSD</summary>
        /// <returns>List of devices</returns>
        internal static DeviceInfo[] GetList()
        {
            string[]          passDevices = Directory.GetFiles("/dev/", "pass*", SearchOption.TopDirectoryOnly);
            List <DeviceInfo> listDevices = new List <DeviceInfo>();

            foreach (string passDevice in passDevices)
            {
                var    deviceInfo = new DeviceInfo();
                IntPtr dev        = cam_open_device(passDevice, FileFlags.ReadWrite);
                var    camDevice  = (CamDevice)Marshal.PtrToStructure(dev, typeof(CamDevice));

                IntPtr ccbPtr = cam_getccb(dev);

                if (ccbPtr.ToInt64() == 0)
                {
                    continue;
                }

                var cgd = (CcbGetdev)Marshal.PtrToStructure(ccbPtr, typeof(CcbGetdev));

                cgd.ccb_h.func_code = XptOpcode.XptGdevType;

                Marshal.StructureToPtr(cgd, ccbPtr, false);

                int error = cam_send_ccb(dev, ccbPtr);

                if (error < 0)
                {
                    cam_freeccb(ccbPtr);

                    continue;
                }

                cgd = (CcbGetdev)Marshal.PtrToStructure(ccbPtr, typeof(CcbGetdev));

                cam_freeccb(ccbPtr);
                cam_close_device(dev);

                string simName = StringHandlers.CToString(camDevice.SimName);
                deviceInfo.Path = passDevice;
                byte[] serialNumber = new byte[camDevice.SerialNumLen];
                Array.Copy(camDevice.SerialNum, 0, serialNumber, 0, serialNumber.Length);
                deviceInfo.Serial = StringHandlers.CToString(serialNumber);

                switch (cgd.protocol)
                {
                case CamProto.ProtoAta:
                case CamProto.ProtoAtapi:
                case CamProto.ProtoSatapm:
                {
                    // Little-endian FreeBSD gives it resorted
                    // Big-endian FreeBSD, no idea
                    byte[] atadTneid = new byte[512];

                    for (int aIndex = 0; aIndex < 512; aIndex += 2)
                    {
                        atadTneid[aIndex]     = cgd.ident_data[aIndex + 1];
                        atadTneid[aIndex + 1] = cgd.ident_data[aIndex];
                    }

                    Identify.IdentifyDevice?idt = Identify.Decode(atadTneid);

                    if (idt.HasValue)
                    {
                        string[] separated = idt.Value.Model.Split(' ');

                        if (separated.Length == 1)
                        {
                            deviceInfo.Vendor = "ATA";
                            deviceInfo.Model  = separated[0];
                        }
                        else
                        {
                            deviceInfo.Vendor = separated[0];
                            deviceInfo.Model  = separated[^ 1];