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); }
internal ComMethodDesc(ITypeInfo typeInfo, FUNCDESC funcDesc) : this(funcDesc.memid) { _hasTypeInfo = true; InvokeKind = funcDesc.invkind; int cNames; string[] rgNames = new string[1 + funcDesc.cParams]; typeInfo.GetNames(_memid, rgNames, rgNames.Length, out cNames); if (IsPropertyPut && rgNames[rgNames.Length - 1] == null) { rgNames[rgNames.Length - 1] = "value"; cNames++; } Debug.Assert(cNames == rgNames.Length); _name = rgNames[0]; _parameters = new ComParamDesc[funcDesc.cParams]; int offset = 0; for (int i = 0; i < funcDesc.cParams; i++) { ELEMDESC elemDesc = (ELEMDESC)Marshal.PtrToStructure( new IntPtr(funcDesc.lprgelemdescParam.ToInt64() + offset), typeof(ELEMDESC)); _parameters[i] = new ComParamDesc(ref elemDesc, rgNames[1 + i]); offset += Marshal.SizeOf(typeof(ELEMDESC)); } }
/// <summary> /// For a given type, analyze all the functions implemented by it. That means all the argument and return types. /// </summary> private void ScanDefinedFunctions(ITypeInfo typeInfo, TYPEATTR typeAttributes) { for (int definedFuncIndex = 0; definedFuncIndex < typeAttributes.cFuncs; definedFuncIndex++) { IntPtr funcDescHandleToRelease = IntPtr.Zero; try { ComReference.GetFuncDescForDescIndex(typeInfo, definedFuncIndex, out FUNCDESC funcDesc, out funcDescHandleToRelease); int offset = 0; // Analyze the argument types for (int paramIndex = 0; paramIndex < funcDesc.cParams; paramIndex++) { var elemDesc = (ELEMDESC)Marshal.PtrToStructure( new IntPtr(funcDesc.lprgelemdescParam.ToInt64() + offset), typeof(ELEMDESC)); AnalyzeElement(typeInfo, elemDesc); offset += Marshal.SizeOf <ELEMDESC>(); } // Analyze the return value type AnalyzeElement(typeInfo, funcDesc.elemdescFunc); } finally { if (funcDescHandleToRelease != IntPtr.Zero) { typeInfo.ReleaseFuncDesc(funcDescHandleToRelease); } } } }
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; } } }
/// <devdoc> /// Copy the native GDI+ EncoderParameters data from a chunk of memory into a managed EncoderParameters object. /// See ConvertToMemory for more info. /// </devdoc> internal static EncoderParameters ConvertFromMemory(IntPtr memory) { if (memory == IntPtr.Zero) { throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter); } int count = Marshal.ReadIntPtr(memory).ToInt32(); EncoderParameters p = new EncoderParameters(count); int size = Marshal.SizeOf(typeof(EncoderParameter)); long arrayOffset = (long)memory + Marshal.SizeOf(typeof(IntPtr)); for (int i = 0; i < count; i++) { Guid guid = (Guid)UnsafeNativeMethods.PtrToStructure((IntPtr)(i * size + arrayOffset), typeof(Guid)); int numberOfValues = Marshal.ReadInt32((IntPtr)(i * size + arrayOffset + 16)); EncoderParameterValueType type = (EncoderParameterValueType)Marshal.ReadInt32((IntPtr)(i * size + arrayOffset + 20)); IntPtr value = Marshal.ReadIntPtr((IntPtr)(i * size + arrayOffset + 24)); p._param[i] = new EncoderParameter(new Encoder(guid), numberOfValues, type, value); } return(p); }
public static string GetDirectoryViaBrowseDialog(this IVsUIShell2 shell, IntPtr parentWindow, Guid persistenceSlot, string title, string initialDirectory, bool overridePersistedInitialDirectory) { if (shell == null) { throw new ArgumentNullException("shell"); } if (title == null) { throw new ArgumentNullException("title"); } const int MaxDirName = 10000; IntPtr dirNameBuffer = Marshal.AllocCoTaskMem((MaxDirName + 1) * sizeof(char)); try { VSBROWSEINFOW[] browse = new VSBROWSEINFOW[] { new VSBROWSEINFOW { pwzDlgTitle = title, dwFlags = (uint)BrowseInfoFlags.ReturnOnlyFileSystemDirectories, hwndOwner = parentWindow, pwzInitialDir = GetInitialDirectoryToUse(initialDirectory, overridePersistedInitialDirectory, persistenceSlot), nMaxDirName = MaxDirName, lStructSize = (uint)Marshal.SizeOf(typeof(VSBROWSEINFOW)), pwzDirName = dirNameBuffer, dwHelpTopic = 0 } }; string helpTopic = string.Empty; string openButtonLabel = null; string ceilingDir = null; VSNSEBROWSEINFOW[] nseBrowseInfo = null; ErrorHandler.ThrowOnFailure(shell.GetDirectoryViaBrowseDlgEx(browse, helpTopic, openButtonLabel, ceilingDir, nseBrowseInfo)); string folder = Marshal.PtrToStringUni(browse[0].pwzDirName); if (!string.IsNullOrEmpty(folder)) { PersistLastUseDirectory(persistenceSlot, folder); } return(folder); } catch (COMException ex) when(ex.ErrorCode == VSConstants.OLE_E_PROMPTSAVECANCELLED) { } finally { if (dirNameBuffer != IntPtr.Zero) { Marshal.FreeCoTaskMem(dirNameBuffer); dirNameBuffer = IntPtr.Zero; } } return(null); }
public static int SizeOf <T>() { #if NET45 return(SystemMarshal.SizeOf(typeof(T))); #else return(SystemMarshal.SizeOf <T>()); #endif }
public TYPEDESC CreateTypeDesc(IntPtr finalTypeHRef, MockUnmanagedMemoryHelper memoryHelper) { TYPEDESC typeDesc; typeDesc.vt = (short)VarEnum.VT_PTR; typeDesc.lpValue = memoryHelper.AllocateHandle(Marshal.SizeOf <TYPEDESC>()); Marshal.StructureToPtr(_baseElementType.CreateTypeDesc(finalTypeHRef, memoryHelper), typeDesc.lpValue, false); return(typeDesc); }
public void GetLibAttr(out IntPtr ppTLibAttr) { // 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.ITypeLib_GetLibAttr); ppTLibAttr = _memoryHelper.AllocateHandle(Marshal.SizeOf(typeof(TYPELIBATTR))); Marshal.StructureToPtr(this.Attributes, ppTLibAttr, false); }
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 !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(); if (myHandle.IsInvalid) { if (null != name && 0 != name.Length && NativeMethods.ERROR_INVALID_HANDLE == errorCode) { throw new WaitHandleCannotBeOpenedException(SR.GetString(SR.WaitHandleCannotBeOpenedException_InvalidHandle, name)); } InternalResources.WinIOError(); } createdNew = errorCode != NativeMethods.ERROR_ALREADY_EXISTS; this.SafeWaitHandle = myHandle; }
private int _GetPointId(IntPtr pointCloudHandle, int index) { IntPtr pointCloudIdsHandle = IntPtr.Zero; ExternApi.ArPointCloud_getPointIds(m_NativeSession.SessionHandle, pointCloudHandle, ref pointCloudIdsHandle); IntPtr pointIdHandle = new IntPtr(pointCloudIdsHandle.ToInt64() + (Marshal.SizeOf(typeof(int)) * index)); return(Marshal.ReadInt32(pointIdHandle)); }
public Vector4 GetPoint(IntPtr pointCloudHandle, int index) { IntPtr pointCloudNativeHandle = IntPtr.Zero; ExternApi.ArPointCloud_getData(m_NativeSession.SessionHandle, pointCloudHandle, ref pointCloudNativeHandle); IntPtr pointHandle = new IntPtr(pointCloudNativeHandle.ToInt64() + (Marshal.SizeOf(typeof(Vector4)) * index)); Marshal.Copy(pointHandle, m_CachedVector, 0, 4); // Negate z axis because points are returned in OpenGl space. return(new Vector4(m_CachedVector[0], m_CachedVector[1], -m_CachedVector[2], m_CachedVector[3])); }
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); } } } }
public PointCloudPoint GetPoint(IntPtr pointCloudHandle, int index) { // Get a reference to the pointcloud data to extract position and condfidence of point at index. IntPtr pointCloudDataHandle = IntPtr.Zero; ExternApi.ArPointCloud_getData(m_NativeSession.SessionHandle, pointCloudHandle, ref pointCloudDataHandle); IntPtr pointDataHandle = new IntPtr(pointCloudDataHandle.ToInt64() + (Marshal.SizeOf(typeof(Vector4)) * index)); Marshal.Copy(pointDataHandle, m_CachedVector, 0, 4); // Negate z axis because points are returned in OpenGl space. Vector3 position = new Vector3(m_CachedVector[0], m_CachedVector[1], -m_CachedVector[2]); float confidence = m_CachedVector[3]; return(new PointCloudPoint(_GetPointId(pointCloudHandle, index), position, confidence)); }
public void GetVarDesc(int index, out IntPtr ppVarDesc) { // 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_GetVarDesc); ppVarDesc = _memoryHelper.AllocateHandle(Marshal.SizeOf <VARDESC>()); _memoryHelper.EnterSubAllocationScope(ppVarDesc); VARDESC varDesc = new VARDESC(); varDesc.elemdescVar.tdesc = _definedVariables[index].CreateTypeDesc(new IntPtr(index + s_HREF_VARS_OFFSET), _memoryHelper); _memoryHelper.ExitSubAllocationScope(); Marshal.StructureToPtr(varDesc, ppVarDesc, false); }
/// <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); }
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); }
public static int SizeOf <T>() { return(SystemMarshal.SizeOf <T>()); }
/// <summary> /// 構造体を Stream に書き込みます。 /// </summary> /// <param name="structure">書き込む構造体を指定します。</param> /// <param name="length"> /// 書き込む長さを指定します。構造体の初めから途中までの情報を書き込む事が出来ます。 /// 構造体自体の長さよりも大きな値を指定した場合にはエラーになります。 /// </param> public void WriteStructure(System.ValueType structure, int length) { int len = Marshal.SizeOf(structure); this.WriteStructure(structure, len, length); }
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(BuildPropertyNames.DeploymentString, true)); var xLaunch = (LaunchType)Enum.Parse(typeof(LaunchType), GetConfigurationProperty(BuildPropertyNames.LaunchString, false)); var xVSDebugPort = GetConfigurationProperty(BuildPropertyNames.VisualStudioDebugPortString, 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(BuildPropertyNames.PxeInterfaceString, false); File.Copy(xBinFile, Path.Combine(xPxePath, "Cosmos.bin"), true); Process.Start(Path.Combine(CosmosPaths.Tools, "Cosmos.Deploy.Pixie.exe"), xPxeIntf + " \"" + xPxePath + "\""); } else if (xDeployment == DeploymentType.BinaryImage) { // prepare? } else { throw new Exception("Unknown deployment type."); } if (xLaunch == LaunchType.None && 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); }
/// <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; } }