コード例 #1
0
        public static int LaunchDebugTargets(this IVsDebugger2 debugger, params VsDebugTargetInfo2[] targets)
        {
            IntPtr ptr             = IntPtr.Zero;
            int    marshalledCount = 0;

            try
            {
                ptr = Marshal.AllocHGlobal(targets.Length * Marshal.SizeOf(typeof(VsDebugTargetInfo2)));
                for (int i = 0; i < targets.Length; i++)
                {
                    IntPtr current = new IntPtr(ptr.ToInt64() + i * Marshal.SizeOf(typeof(VsDebugTargetInfo2)));
                    Marshal.StructureToPtr(targets[i], current, false);
                    marshalledCount++;
                }

                return(debugger.LaunchDebugTargets2((uint)targets.Length, ptr));
            }
            finally
            {
                if (ptr != IntPtr.Zero)
                {
                    for (int i = 0; i < marshalledCount; i++)
                    {
                        IntPtr current = new IntPtr(ptr.ToInt64() + i * Marshal.SizeOf(typeof(VsDebugTargetInfo2)));
                        Marshal.DestroyStructure(current, typeof(VsDebugTargetInfo2));
                    }

                    Marshal.FreeHGlobal(ptr);
                    ptr = IntPtr.Zero;
                }
            }
        }
コード例 #2
0
        public override void CommitChanges()
        {
            if (IsReadOnly)
            {
                throw new InvalidOperationException("Changes cannot be commited because the current ResourceSource is read-only");
            }

            // Unload self
            if (LoadMode > 0)
            {
                Unload();
            }

            IntPtr updateHandle = NativeMethods.BeginUpdateResource(_path, false);

            foreach (ResourceLang lang in AllActiveLangs)
            {
                IntPtr pData;
                Int32  length;

                if (lang.Action == ResourceDataAction.Delete)
                {
                    // pData must be NULL to delete resource
                    pData  = IntPtr.Zero;
                    length = 0;
                }
                else
                {
                    if (!lang.DataIsLoaded)
                    {
                        throw new AnolisException("Cannot perform action when ResourceData is not loaded");
                    }

                    length = lang.Data.RawData.Length;
                    pData  = Marshal.AllocHGlobal(length);

                    Marshal.Copy(lang.Data.RawData, 0, pData, length);
                }

                IntPtr typeId = lang.Name.Type.Identifier.NativeId;
                IntPtr nameId = lang.Name.Identifier.NativeId;
                ushort langId = lang.LanguageId;

                NativeMethods.UpdateResource(updateHandle, typeId, nameId, langId, pData, length);

                Marshal.FreeHGlobal(pData);

                lang.Action = ResourceDataAction.None;
            }

            NativeMethods.EndUpdateResource(updateHandle, false);

            if (LoadMode > 0)
            {
                Reload();
            }
        }
コード例 #3
0
ファイル: ID3v2.cs プロジェクト: akinomyoga/afh
 /// <summary>
 /// 構造体を Stream に書き込みます。動作確認済み。
 /// </summary>
 /// <param name="structure">書き込む構造体を指定します。</param>
 /// <param name="strlen">構造体の長さを指定します。</param>
 /// <param name="copylen">書き込む長さを指定します。</param>
 private void WriteStructure(System.ValueType structure, int strlen, int copylen)
 {
     System.IntPtr buff = Marshal.AllocHGlobal(strlen);
     try{
         byte[] data = new byte[copylen];
         Marshal.StructureToPtr(structure, buff, false);
         Marshal.Copy(buff, data, 0, strlen);
         str.Write(data, 0, copylen);
     }finally{
         Marshal.FreeHGlobal(buff);
     }
 }
コード例 #4
0
        private void CommitChangesImpl()
        {
            IntPtr updateHandle = NativeMethods.BeginUpdateResource(FileInfo.FullName, false);

            foreach (ResourceLang lang in AllActiveLangs)
            {
                IntPtr pData;
                Int32  length;

                if (lang.Action == ResourceDataAction.Delete)
                {
                    // pData must be NULL to delete resource
                    pData  = IntPtr.Zero;
                    length = 0;
                }
                else
                {
                    if (!lang.DataIsLoaded)
                    {
                        throw new AnolisException("Cannot perform action when ResourceData is not loaded");
                    }

                    length = lang.Data.RawData.Length;
                    pData  = Marshal.AllocHGlobal(length);

                    Marshal.Copy(lang.Data.RawData, 0, pData, length);
                }

                IntPtr typeId = lang.Name.Type.Identifier.NativeId;
                IntPtr nameId = lang.Name.Identifier.NativeId;
                ushort langId = lang.LanguageId;

                Boolean uSuccess = NativeMethods.UpdateResource(updateHandle, typeId, nameId, langId, pData, length);
                if (!uSuccess)
                {
                    throw new AnolisException("UpdatedResource failed: " + NativeMethods.GetLastErrorString());
                }

                Marshal.FreeHGlobal(pData);

                lang.Action = ResourceDataAction.None;
            }

            Boolean success = NativeMethods.EndUpdateResource(updateHandle, false);

            if (!success)
            {
                throw new AnolisException("EndUpdateResource failed: " + NativeMethods.GetLastErrorString());
            }
        }
コード例 #5
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);
                    }
                }
            }
        }
コード例 #6
0
        /// <summary>
        /// Allocate a native handle for a buffer of cb bytes
        /// </summary>
        /// <param name="cb"></param>
        /// <returns></returns>
        public IntPtr AllocateHandle(int cb)
        {
            IntPtr handle = Marshal.AllocHGlobal(cb);

            // If this is a dependent allocation, add it to the list of dependencies
            if (_mainAllocationHandle != IntPtr.Zero)
            {
                if (!_dependentAllocations.ContainsKey(_mainAllocationHandle))
                {
                    _dependentAllocations.Add(_mainAllocationHandle, new List <IntPtr>());
                }

                _dependentAllocations[_mainAllocationHandle].Add(handle);
            }
            else
            {
                _allocatedHandles.Add(handle);
            }

            return(handle);
        }
コード例 #7
0
ファイル: EncoderParameters.cs プロジェクト: xuanmu/corefx
        /// <devdoc>
        ///     Copy the EncoderParameters data into a chunk of memory to be consumed by native GDI+ code.
        ///
        ///     We need to marshal the EncoderParameters info from/to native GDI+ ourselve since the definition of the managed/unmanaged classes
        ///     are different and the native class is a bit weird. The native EncoderParameters class is defined in GDI+ as follows:
        ///
        ///      class EncoderParameters {
        ///          UINT Count;                      // Number of parameters in this structure
        ///          EncoderParameter Parameter[1];   // Parameter values
        ///      };
        ///
        ///     We don't have the 'Count' field since the managed array contains it. In order for this structure to work with more than one
        ///     EncoderParameter we need to preallocate memory for the extra n-1 elements, something like this:
        ///
        ///         EncoderParameters* pEncoderParameters = (EncoderParameters*) malloc(sizeof(EncoderParameters) + (n-1) * sizeof(EncoderParameter));
        ///
        ///     Also, in 64-bit platforms, 'Count' is aligned in 8 bytes (4 extra padding bytes) so we use IntPtr instead of Int32 to account for
        ///     that.
        /// </devdoc>
        internal IntPtr ConvertToMemory()
        {
            int size = Marshal.SizeOf(typeof(EncoderParameter));

            int    length = _param.Length;
            IntPtr memory = Marshal.AllocHGlobal(checked (length * size + Marshal.SizeOf(typeof(IntPtr))));

            if (memory == IntPtr.Zero)
            {
                throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
            }

            Marshal.WriteIntPtr(memory, (IntPtr)length);

            long arrayOffset = checked ((long)memory + Marshal.SizeOf(typeof(IntPtr)));

            for (int i = 0; i < length; i++)
            {
                Marshal.StructureToPtr(_param[i], (IntPtr)(arrayOffset + i * size), false);
            }

            return(memory);
        }
コード例 #8
0
ファイル: Constructor.cs プロジェクト: morefun0302/Aaru
        /// <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;

            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);

                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);
            }

            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 = ConvertFromHexAscii("/sys/block/" + devPath + "/device/csd", out _cachedCsd);

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

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

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

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

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

                        if (File.Exists("/sys/block/" + devPath + "/device/ocr"))
                        {
                            int len = ConvertFromHexAscii("/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;
                }
            }
コード例 #9
0
        protected virtual void LoadImages(List <Image> images)
        {
            Debug.Assert(images.Count >= 1);
            if (isLoaded)
            {
                log.InfoFormat("Unloading image: {0}", name);
                Unload();
            }
            srcWidth  = width = images[0].Width;
            srcHeight = height = images[0].Height;
            srcDepth  = depth = images[0].Depth;
            if (hasAlpha && images[0].Format == PixelFormat.L8)
            {
                format = PixelFormat.A8;
                srcBpp = 8;
            }
            else
            {
                this.Format = images[0].Format;
            }
            if (finalBpp == 16)
            {
                switch (format)
                {
                case PixelFormat.R8G8B8:
                case PixelFormat.X8R8G8B8:
                    format = PixelFormat.R5G6B5;
                    break;

                case PixelFormat.B8G8R8:
                case PixelFormat.X8B8G8R8:
                    format = PixelFormat.B5G6R5;
                    break;

                case PixelFormat.A8R8G8B8:
                case PixelFormat.R8G8B8A8:
                case PixelFormat.A8B8G8R8:
                case PixelFormat.B8G8R8A8:
                    format = PixelFormat.A4R4G4B4;
                    break;

                default:
                    // use the original format
                    break;
                }
            }

            // The custom mipmaps in the image have priority over everything
            int imageMips = images[0].NumMipMaps;

            if (imageMips > 0)
            {
                numMipmaps = imageMips;
                usage     &= ~TextureUsage.AutoMipMap;
            }

            // Create the texture
            CreateInternalResources();

            // Check if we're loading one image with multiple faces
            // or a vector of images representing the faces
            int  faces;
            bool multiImage;         // Load from multiple images?

            if (images.Count > 1)
            {
                faces      = images.Count;
                multiImage = true;
            }
            else
            {
                faces      = images[0].NumFaces;
                multiImage = false;
            }

            // Check wether number of faces in images exceeds number of faces
            // in this texture. If so, clamp it.
            if (faces > this.NumFaces)
            {
                faces = this.NumFaces;
            }

            // Say what we're doing
            log.InfoFormat("Texture: {0}: Loading {1} faces({2},{3}x{4}x{5})",
                           name, faces, PixelUtil.GetFormatName(images[0].Format),
                           images[0].Width, images[0].Height, images[0].Depth);
#if NOT // crazy ogre logging
            if (!(mMipmapsHardwareGenerated && mNumMipmaps == 0))
            {
                str << mNumMipmaps;
            }
            if (mUsage & TU_AUTOMIPMAP)
            {
                if (mMipmapsHardwareGenerated)
                {
                    str << " hardware";
                }

                str << " generated mipmaps";
            }
            else
            {
                str << " custom mipmaps";
            }
            if (multiImage)
            {
                str << " from multiple Images.";
            }
            else
            {
                str << " from Image.";
            }
            // Scoped
            {
                // Print data about first destination surface
                HardwarePixelBufferSharedPtr buf = getBuffer(0, 0);
                str << " Internal format is " << PixelUtil::getFormatName(buf->getFormat()) <<
                    "," << buf->getWidth() << "x" << buf->getHeight() << "x" << buf->getDepth() << ".";
            }
            LogManager::getSingleton().logMessage(
                LML_NORMAL, str.str());
#endif
            // Main loading loop
            // imageMips == 0 if the image has no custom mipmaps, otherwise contains the number of custom mips
            for (int mip = 0; mip <= imageMips; ++mip)
            {
                for (int i = 0; i < faces; ++i)
                {
                    PixelBox src;
                    if (multiImage)
                    {
                        // Load from multiple images
                        src = images[i].GetPixelBox(0, mip);
                    }
                    else
                    {
                        // Load from faces of images[0]
                        src = images[0].GetPixelBox(i, mip);

                        if (hasAlpha && src.Format == PixelFormat.L8)
                        {
                            src.Format = PixelFormat.A8;
                        }
                    }

                    if (gamma != 1.0f)
                    {
                        // Apply gamma correction
                        // Do not overwrite original image but do gamma correction in temporary buffer
                        IntPtr buffer = Marshal.AllocHGlobal(PixelUtil.GetMemorySize(src.Width, src.Height, src.Depth, src.Format));
                        try {
                            PixelBox corrected = new PixelBox(src.Width, src.Height, src.Depth, src.Format, buffer);
                            PixelUtil.BulkPixelConversion(src, corrected);

                            Image.ApplyGamma(corrected.Data, gamma, corrected.ConsecutiveSize, PixelUtil.GetNumElemBits(src.Format));

                            // Destination: entire texture. BlitFromMemory does the scaling to
                            // a power of two for us when needed
                            GetBuffer(i, mip).BlitFromMemory(corrected);
                        } finally {
                            Marshal.FreeHGlobal(buffer);
                        }
                    }
                    else
                    {
                        // Destination: entire texture. BlitFromMemory does the scaling to
                        // a power of two for us when needed
                        GetBuffer(i, mip).BlitFromMemory(src);
                    }
                }
            }
            // Update size (the final size, not including temp space)
            size = this.NumFaces * PixelUtil.GetMemorySize(width, height, depth, format);

            isLoaded = true;
        }
コード例 #10
0
 static CameraApi()
 {
     _totalBufferSize = TextureWidth * TextureHeight * (BitsPerPixel / 8);
     RawPixelBuffer   = Marshal.AllocHGlobal(_totalBufferSize);
     _rgbTexture      = new Texture(TextureWidth, TextureHeight, TextureFormat, EnableMipmap);
 }
コード例 #11
0
ファイル: ListDevices.cs プロジェクト: paulyc/Aaru
        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);
        }