diff --git a/src/01/KSociety.SharpCubeProgrammer/CubeProgrammerApi.cs b/src/01/KSociety.SharpCubeProgrammer/CubeProgrammerApi.cs index f84767c..5cade1f 100644 --- a/src/01/KSociety.SharpCubeProgrammer/CubeProgrammerApi.cs +++ b/src/01/KSociety.SharpCubeProgrammer/CubeProgrammerApi.cs @@ -7,7 +7,6 @@ namespace SharpCubeProgrammer using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; - using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; @@ -20,21 +19,11 @@ namespace SharpCubeProgrammer public class CubeProgrammerApi : ICubeProgrammerApi { - /// - /// Synchronization object to protect loading the native library and its functions. This field is read-only. - /// - private readonly object _syncRoot = new object(); - - private Native.SafeLibraryHandle _handleSTLinkDriver; - private Native.SafeLibraryHandle _handleProgrammer; - private readonly ILogger _logger; private const int DisposedFlag = 1; private int _isDisposed; - private static DisplayCallBacks DisplayCallBacks = new DisplayCallBacks(); - #region [Constructor] public CubeProgrammerApi(ILogger logger = default) @@ -45,141 +34,10 @@ public CubeProgrammerApi(ILogger logger = default) } this._logger = logger; - - this.Init(); } #endregion - private void Init() - { - var currentDirectory = GetAssemblyDirectory(); - var target = Path.Combine(currentDirectory, "dll", Environment.Is64BitProcess ? "x64" : "x86"); - - this.LoadStLinkDriver(target); - this.LoadProgrammer(target); - } - - private void LoadStLinkDriver(string target) - { - //var currentDirectory = GetAssemblyDirectory(); - //var target = Path.Combine(currentDirectory, "dll", Environment.Is64BitProcess ? "x64" : "x86"); - - if (this._handleSTLinkDriver == null) - { - lock (this._syncRoot) - { - if (this._handleSTLinkDriver == null) - { -#if NET - if (!NativeLibrary.TryLoad( - target + @"\STLinkUSBDriver.dll", - typeof(CubeProgrammerApi).Assembly, - DllImportSearchPath.UserDirectories, - out IntPtr handle)) - { - var error = Marshal.GetLastWin32Error(); - this._logger?.LogError("Loading with NativeLibrary {0} {1} library error: {2} !", target + @"\STLinkUSBDriver.dll", Environment.Is64BitProcess ? "x64" : "x86", error); - this._handleSTLinkDriver = null; - } - else - { - this._handleSTLinkDriver = new Native.SafeLibraryHandle(handle); - this._logger?.LogInformation("Loading with NativeLibrary {0} - {1} library.", "STLinkUSBDriver.dll", Environment.Is64BitProcess ? "x64" : "x86"); - } -#else - // Check if the local machine has KB2533623 installed in order - // to use the more secure flags when calling LoadLibraryEx - bool hasKB2533623; - - using (var hModule = Native.Utility.LoadLibraryEx(Native.Utility.KernelLibName, IntPtr.Zero, 0)) - { - // If the AddDllDirectory function is found then the flags are supported - hasKB2533623 = Native.Utility.GetProcAddress(hModule, "AddDllDirectory") != IntPtr.Zero; - } - - var dwFlags = 0; - - if (hasKB2533623) - { - // If KB2533623 is installed then specify the more secure LOAD_LIBRARY_SEARCH_DEFAULT_DIRS in dwFlags - dwFlags = Native.Utility.LOAD_LIBRARY_SEARCH_DEFAULT_DIRS; - } - - this._handleSTLinkDriver = Native.Utility.LoadLibraryEx(target + @"\STLinkUSBDriver.dll", IntPtr.Zero, dwFlags); - - if (this._handleSTLinkDriver.IsInvalid) - { - var error = Marshal.GetLastWin32Error(); - this._logger?.LogError("Loading {0} {1} library error: {2} !", target + @"\STLinkUSBDriver.dll", Environment.Is64BitProcess ? "x64" : "x86", error); - this._handleSTLinkDriver = null; - } - else - { - this._logger?.LogInformation("Loading {0} - {1} library.", "STLinkUSBDriver.dll", Environment.Is64BitProcess ? "x64" : "x86"); - } -#endif - } - } - } - } - - private void LoadProgrammer(string target) - { - //var currentDirectory = GetAssemblyDirectory(); - //var target = Path.Combine(currentDirectory, "dll", Environment.Is64BitProcess ? "x64" : "x86"); - - if (this._handleProgrammer == null) - { - lock (this._syncRoot) - { - if (this._handleProgrammer == null) - { -#if NET - if (!NativeLibrary.TryLoad( - target + @"\Programmer.dll", - typeof(CubeProgrammerApi).Assembly, - DllImportSearchPath.UserDirectories, - out IntPtr handle)) - { - var error = Marshal.GetLastWin32Error(); - this._logger?.LogError("Loading with NativeLibrary {0} {1} library error: {2} !", target, Environment.Is64BitProcess ? "x64" : "x86", error); - this._handleProgrammer = null; - } - else - { - this._handleProgrammer = new Native.SafeLibraryHandle(handle); - this._logger?.LogInformation("Loading with NativeLibrary {0} - {1} library.", "Programmer.dll", Environment.Is64BitProcess ? "x64" : "x86"); - } -#else - var dwFlags = Native.Utility.LOAD_WITH_ALTERED_SEARCH_PATH; - - this._handleProgrammer = Native.Utility.LoadLibraryEx(target + @"\Programmer.dll", IntPtr.Zero, dwFlags); - - if (this._handleProgrammer.IsInvalid) - { - var error = Marshal.GetLastWin32Error(); - this._logger?.LogError("Loading {0} {1} library error: {2} !", target + @"\Programmer.dll", Environment.Is64BitProcess ? "x64" : "x86", error); - this._handleProgrammer = null; - } - else - { - this._logger?.LogInformation("Loading {0} - {1} library.", "Programmer.dll", Environment.Is64BitProcess ? "x64" : "x86"); - } -#endif - } - } - } - } - - private static string GetAssemblyDirectory() - { - var codeBase = Assembly.GetExecutingAssembly().Location; - var uri = new UriBuilder(codeBase); - var path = Uri.UnescapeDataString(uri.Path); - return Path.GetDirectoryName(path); - } - #region [ST-LINK] //ST-LINK module groups debug ports JTAG/SWD functions together. @@ -191,9 +49,12 @@ public CubeProgrammerError TryConnectStLink(int stLinkProbeIndex = 0, int shared try { - var connectStLinkResult = Native.ProgrammerApi.TryConnectStLink(stLinkProbeIndex, shared, debugConnectMode); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var connectStLinkResult = Native.ProgrammerApi.TryConnectStLink(stLinkProbeIndex, shared, debugConnectMode); - output = this.CheckResult(connectStLinkResult); + output = this.CheckResult(connectStLinkResult); + } } catch (Exception ex) { @@ -211,20 +72,23 @@ public IEnumerable GetStLinkList(bool shared = false) try { - var size = Marshal.SizeOf(); - var numberOfItems = Native.ProgrammerApi.GetStLinkList(ref listPtr, shared ? 1 : 0); - if (listPtr != IntPtr.Zero) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - for (var i = 0; i < numberOfItems; i++) + var size = Marshal.SizeOf(); + var numberOfItems = Native.ProgrammerApi.GetStLinkList(ref listPtr, shared ? 1 : 0); + if (listPtr != IntPtr.Zero) { - var currentItem = Marshal.PtrToStructure(listPtr + (i * size)); - parametersList.Add(currentItem); - Marshal.DestroyStructure(listPtr + (i * size)); + for (var i = 0; i < numberOfItems; i++) + { + var currentItem = Marshal.PtrToStructure(listPtr + (i * size)); + parametersList.Add(currentItem); + Marshal.DestroyStructure(listPtr + (i * size)); + } + } + else + { + this._logger?.LogWarning("GetStLinkList IntPtr: {0}!", "Zero"); } - } - else - { - this._logger?.LogWarning("GetStLinkList IntPtr: {0}!", "Zero"); } } catch (Exception ex) @@ -243,21 +107,24 @@ public IEnumerable GetStLinkEnumerationList(bool shared try { - var size = Marshal.SizeOf(); - var numberOfItems = Native.ProgrammerApi.GetStLinkEnumerationList(ref listPtr, shared ? 1 : 0); - if (listPtr != IntPtr.Zero) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - for (var i = 0; i < numberOfItems; i++) + var size = Marshal.SizeOf(); + var numberOfItems = Native.ProgrammerApi.GetStLinkEnumerationList(ref listPtr, shared ? 1 : 0); + if (listPtr != IntPtr.Zero) + { + for (var i = 0; i < numberOfItems; i++) + { + var currentItem = Marshal.PtrToStructure(listPtr + (i * size)); + parametersList.Add(currentItem); + Marshal.DestroyStructure(listPtr + (i * size)); + } + } + else { - var currentItem = Marshal.PtrToStructure(listPtr + (i * size)); - parametersList.Add(currentItem); - Marshal.DestroyStructure(listPtr + (i * size)); + this._logger?.LogWarning("GetStLinkEnumerationList IntPtr: {0}!", "Zero"); } } - else - { - this._logger?.LogWarning("GetStLinkEnumerationList IntPtr: {0}!", "Zero"); - } } catch (Exception ex) { @@ -274,9 +141,12 @@ public CubeProgrammerError ConnectStLink(DebugConnectParameters debugConnectPara try { - var connectStLinkResult = Native.ProgrammerApi.ConnectStLink(debugConnectParameters); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var connectStLinkResult = Native.ProgrammerApi.ConnectStLink(debugConnectParameters); - output = this.CheckResult(connectStLinkResult); + output = this.CheckResult(connectStLinkResult); + } } catch (Exception ex) { @@ -289,8 +159,20 @@ public CubeProgrammerError ConnectStLink(DebugConnectParameters debugConnectPara /// public CubeProgrammerError Reset(DebugResetMode rstMode) { - var resetResult = Native.ProgrammerApi.Reset(rstMode); - var output = this.CheckResult(resetResult); + var output = CubeProgrammerError.CubeprogrammerErrorOther; + + try + { + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var resetResult = Native.ProgrammerApi.Reset(rstMode); + output = this.CheckResult(resetResult); + } + } + catch (Exception ex) + { + this._logger?.LogError(ex, "ConnectStLink: "); + } return output; } @@ -307,22 +189,25 @@ public IEnumerable GetUsartList() var parametersList = new List(); try { - var numberOfItems = Native.ProgrammerApi.GetUsartList(ref listPtr); - if (numberOfItems > 0) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - if (listPtr != IntPtr.Zero) + var numberOfItems = Native.ProgrammerApi.GetUsartList(ref listPtr); + if (numberOfItems > 0) { - var size = Marshal.SizeOf(); - for (var i = 0; i < numberOfItems; i++) + if (listPtr != IntPtr.Zero) { - var currentItem = Marshal.PtrToStructure(listPtr + (i * size)); - parametersList.Add(currentItem); - Marshal.DestroyStructure(listPtr + (i * size)); + var size = Marshal.SizeOf(); + for (var i = 0; i < numberOfItems; i++) + { + var currentItem = Marshal.PtrToStructure(listPtr + (i * size)); + parametersList.Add(currentItem); + Marshal.DestroyStructure(listPtr + (i * size)); + } + } + else + { + this._logger?.LogWarning("GetUsartList IntPtr: {0}!", "Zero"); } - } - else - { - this._logger?.LogWarning("GetUsartList IntPtr: {0}!", "Zero"); } } } @@ -340,9 +225,12 @@ public CubeProgrammerError ConnectUsartBootloader(UsartConnectParameters usartCo try { - var connectUsartResult = Native.ProgrammerApi.ConnectUsartBootloader(usartConnectParameters); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var connectUsartResult = Native.ProgrammerApi.ConnectUsartBootloader(usartConnectParameters); - output = this.CheckResult(connectUsartResult); + output = this.CheckResult(connectUsartResult); + } } catch (Exception ex) { @@ -358,9 +246,12 @@ public CubeProgrammerError SendByteUart(int bytes) var output = CubeProgrammerError.CubeprogrammerErrorOther; try { - var connectUsartResult = Native.ProgrammerApi.SendByteUart(bytes); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var connectUsartResult = Native.ProgrammerApi.SendByteUart(bytes); - output = this.CheckResult(connectUsartResult); + output = this.CheckResult(connectUsartResult); + } } catch (Exception ex) { @@ -377,21 +268,24 @@ public int GetDfuDeviceList(ref List dfuDeviceList) try { - var size = Marshal.SizeOf(); - numberOfItems = Native.ProgrammerApi.GetDfuDeviceList(ref listPtr, 0xdf11, 0x0483); - - if (listPtr != IntPtr.Zero) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - for (var i = 0; i < numberOfItems; i++) + var size = Marshal.SizeOf(); + numberOfItems = Native.ProgrammerApi.GetDfuDeviceList(ref listPtr, 0xdf11, 0x0483); + + if (listPtr != IntPtr.Zero) + { + for (var i = 0; i < numberOfItems; i++) + { + var currentItem = Marshal.PtrToStructure(listPtr + (i * size)); + dfuDeviceList.Add(currentItem); + } + } + else { - var currentItem = Marshal.PtrToStructure(listPtr + (i * size)); - dfuDeviceList.Add(currentItem); + this._logger?.LogWarning("GetDfuDeviceList IntPtr: {0}!", "Zero"); } } - else - { - this._logger?.LogWarning("GetDfuDeviceList IntPtr: {0}!", "Zero"); - } } catch (Exception ex) { @@ -407,13 +301,16 @@ public CubeProgrammerError ConnectDfuBootloader(string usbIndex) var output = CubeProgrammerError.CubeprogrammerErrorOther; try { - var connectDfuBootloaderResult = Native.ProgrammerApi.ConnectDfuBootloader(usbIndex); - if (connectDfuBootloaderResult != 0) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - this.Disconnect(); - } + var connectDfuBootloaderResult = Native.ProgrammerApi.ConnectDfuBootloader(usbIndex); + if (connectDfuBootloaderResult != 0) + { + this.Disconnect(); + } - output = this.CheckResult(connectDfuBootloaderResult); + output = this.CheckResult(connectDfuBootloaderResult); + } } catch (Exception ex) { @@ -429,13 +326,16 @@ public CubeProgrammerError ConnectDfuBootloader2(DfuConnectParameters dfuParamet var output = CubeProgrammerError.CubeprogrammerErrorOther; try { - var connectDfuBootloader2Result = Native.ProgrammerApi.ConnectDfuBootloader2(dfuParameters); - if (connectDfuBootloader2Result != 0) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - this.Disconnect(); - } + var connectDfuBootloader2Result = Native.ProgrammerApi.ConnectDfuBootloader2(dfuParameters); + if (connectDfuBootloader2Result != 0) + { + this.Disconnect(); + } - output = this.CheckResult(connectDfuBootloader2Result); + output = this.CheckResult(connectDfuBootloader2Result); + } } catch (Exception ex) { @@ -450,13 +350,16 @@ public CubeProgrammerError ConnectSpiBootloader(SpiConnectParameters spiParamete var output = CubeProgrammerError.CubeprogrammerErrorOther; try { - var connectSpiBootloaderResult = Native.ProgrammerApi.ConnectSpiBootloader(spiParameters); - if (connectSpiBootloaderResult != 0) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - this.Disconnect(); - } + var connectSpiBootloaderResult = Native.ProgrammerApi.ConnectSpiBootloader(spiParameters); + if (connectSpiBootloaderResult != 0) + { + this.Disconnect(); + } - output = this.CheckResult(connectSpiBootloaderResult); + output = this.CheckResult(connectSpiBootloaderResult); + } } catch (Exception ex) { @@ -471,13 +374,16 @@ public CubeProgrammerError ConnectCanBootloader(CanConnectParameters canParamete var output = CubeProgrammerError.CubeprogrammerErrorOther; try { - var connectCanBootloaderResult = Native.ProgrammerApi.ConnectCanBootloader(canParameters); - if (connectCanBootloaderResult != 0) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - this.Disconnect(); - } + var connectCanBootloaderResult = Native.ProgrammerApi.ConnectCanBootloader(canParameters); + if (connectCanBootloaderResult != 0) + { + this.Disconnect(); + } - output = this.CheckResult(connectCanBootloaderResult); + output = this.CheckResult(connectCanBootloaderResult); + } } catch (Exception ex) { @@ -492,13 +398,16 @@ public CubeProgrammerError ConnectI2CBootloader(I2CConnectParameters i2CParamete var output = CubeProgrammerError.CubeprogrammerErrorOther; try { - var connectI2CBootloaderResult = Native.ProgrammerApi.ConnectI2cBootloader(i2CParameters); - if (connectI2CBootloaderResult != 0) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - this.Disconnect(); - } + var connectI2CBootloaderResult = Native.ProgrammerApi.ConnectI2cBootloader(i2CParameters); + if (connectI2CBootloaderResult != 0) + { + this.Disconnect(); + } - output = this.CheckResult(connectI2CBootloaderResult); + output = this.CheckResult(connectI2CBootloaderResult); + } } catch (Exception ex) { @@ -516,45 +425,62 @@ public CubeProgrammerError ConnectI2CBootloader(I2CConnectParameters i2CParamete /// public DisplayCallBacks SetDisplayCallbacks(InitProgressBar initProgressBar, LogMessageReceived messageReceived, ProgressBarUpdateReceived progressBarUpdate) { - DisplayCallBacks.InitProgressBar = initProgressBar; - DisplayCallBacks.LogMessage = messageReceived; - DisplayCallBacks.LoadBar = progressBarUpdate; - Native.ProgrammerApi.SetDisplayCallbacks(DisplayCallBacks); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + Native.ProgrammerApi.DisplayCallBacks.InitProgressBar = initProgressBar; + Native.ProgrammerApi.DisplayCallBacks.LogMessage = messageReceived; + Native.ProgrammerApi.DisplayCallBacks.LoadBar = progressBarUpdate; + Native.ProgrammerApi.SetDisplayCallbacks(Native.ProgrammerApi.DisplayCallBacks); + } - return DisplayCallBacks; + return Native.ProgrammerApi.DisplayCallBacks; } /// public DisplayCallBacks SetDisplayCallbacks(DisplayCallBacks callbacksHandle) { - DisplayCallBacks = callbacksHandle; - Native.ProgrammerApi.SetDisplayCallbacks(DisplayCallBacks); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + Native.ProgrammerApi.DisplayCallBacks = callbacksHandle; + Native.ProgrammerApi.SetDisplayCallbacks(Native.ProgrammerApi.DisplayCallBacks); + } - return DisplayCallBacks; + return Native.ProgrammerApi.DisplayCallBacks; } /// public void SetVerbosityLevel(CubeProgrammerVerbosityLevel level) { - Native.ProgrammerApi.SetVerbosityLevel((int)level); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + Native.ProgrammerApi.SetVerbosityLevel((int)level); + } } /// public bool CheckDeviceConnection() { - var checkDeviceConnectionResult = Native.ProgrammerApi.CheckDeviceConnection(); - return checkDeviceConnectionResult; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var checkDeviceConnectionResult = Native.ProgrammerApi.CheckDeviceConnection(); + return checkDeviceConnectionResult; + } + + return false; } /// public GeneralInf? GetDeviceGeneralInf() { GeneralInf? generalInf = null; - var pointer = Native.ProgrammerApi.GetDeviceGeneralInf(); - + try { - generalInf = Marshal.PtrToStructure(pointer); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var pointer = Native.ProgrammerApi.GetDeviceGeneralInf(); + generalInf = Marshal.PtrToStructure(pointer); + } } catch (Exception ex) { @@ -573,14 +499,17 @@ public bool CheckDeviceConnection() try { - var bufferPtr = IntPtr.Zero; - var readMemoryResult = - Native.ProgrammerApi.ReadMemory(uintAddress, ref bufferPtr, Convert.ToUInt32(byteSize)); - result = this.CheckResult(readMemoryResult); - if (bufferPtr != IntPtr.Zero) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - Marshal.Copy(bufferPtr, buffer, 0, byteSize); - this.FreeLibraryMemory(bufferPtr); + var bufferPtr = IntPtr.Zero; + var readMemoryResult = + Native.ProgrammerApi.ReadMemory(uintAddress, ref bufferPtr, Convert.ToUInt32(byteSize)); + result = this.CheckResult(readMemoryResult); + if (bufferPtr != IntPtr.Zero) + { + Marshal.Copy(bufferPtr, buffer, 0, byteSize); + this.FreeLibraryMemory(bufferPtr); + } } } catch (Exception ex) @@ -602,12 +531,15 @@ public CubeProgrammerError WriteMemory(string address, byte[] data) try { - var gch = GCHandle.Alloc(data, GCHandleType.Pinned); - var writeMemoryResult = Native.ProgrammerApi.WriteMemory(uintAddress, gch.AddrOfPinnedObject(), (uint)data.Length); - gch.Free(); - result = this.CheckResult(writeMemoryResult); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var gch = GCHandle.Alloc(data, GCHandleType.Pinned); + var writeMemoryResult = Native.ProgrammerApi.WriteMemory(uintAddress, gch.AddrOfPinnedObject(), (uint)data.Length); + gch.Free(); + result = this.CheckResult(writeMemoryResult); - return result; + return result; + } } catch (Exception ex) { @@ -629,12 +561,15 @@ public CubeProgrammerError WriteMemoryAutoFill(string address, byte[] data) try { - var gch = GCHandle.Alloc(data, GCHandleType.Pinned); - var writeMemoryResult = Native.ProgrammerApi.WriteMemoryAutoFill(uintAddress, gch.AddrOfPinnedObject(), (uint)data.Length); - gch.Free(); - result = this.CheckResult(writeMemoryResult); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var gch = GCHandle.Alloc(data, GCHandleType.Pinned); + var writeMemoryResult = Native.ProgrammerApi.WriteMemoryAutoFill(uintAddress, gch.AddrOfPinnedObject(), (uint)data.Length); + gch.Free(); + result = this.CheckResult(writeMemoryResult); - return result; + return result; + } } catch (Exception ex) { @@ -656,12 +591,15 @@ public CubeProgrammerError WriteMemoryAndVerify(string address, byte[] data) try { - var gch = GCHandle.Alloc(data, GCHandleType.Pinned); - var writeMemoryResult = Native.ProgrammerApi.WriteMemoryAndVerify(uintAddress, gch.AddrOfPinnedObject(), (uint)data.Length); - gch.Free(); - result = this.CheckResult(writeMemoryResult); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var gch = GCHandle.Alloc(data, GCHandleType.Pinned); + var writeMemoryResult = Native.ProgrammerApi.WriteMemoryAndVerify(uintAddress, gch.AddrOfPinnedObject(), (uint)data.Length); + gch.Free(); + result = this.CheckResult(writeMemoryResult); - return result; + return result; + } } catch (Exception ex) { @@ -681,14 +619,16 @@ public CubeProgrammerError EditSector(string address, byte[] data) { var uintAddress = this.HexConverterToUint(address); - var gch = GCHandle.Alloc(data, GCHandleType.Pinned); - - var writeMemoryResult = Native.ProgrammerApi.EditSector(uintAddress, gch.AddrOfPinnedObject(), (uint)data.Length); - gch.Free(); - result = this.CheckResult(writeMemoryResult); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var gch = GCHandle.Alloc(data, GCHandleType.Pinned); + var writeMemoryResult = Native.ProgrammerApi.EditSector(uintAddress, gch.AddrOfPinnedObject(), (uint)data.Length); + gch.Free(); + result = this.CheckResult(writeMemoryResult); - return result; + return result; + } } return result; @@ -723,14 +663,17 @@ public CubeProgrammerError DownloadFile(string inputFilePath, string address = " try { - var downloadFileResult = Native.ProgrammerApi.DownloadFile( + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var downloadFileResult = Native.ProgrammerApi.DownloadFile( filePathAdapted, uintAddress, skipErase, verify, binPathAdapted - ); - output = this.CheckResult(downloadFileResult); + ); + output = this.CheckResult(downloadFileResult); + } } catch (Exception ex) { @@ -747,10 +690,13 @@ public CubeProgrammerError Execute(string address = "0x08000000") try { - var uintAddress = this.HexConverterToUint(address); - var executeResult = Native.ProgrammerApi.Execute(uintAddress); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var uintAddress = this.HexConverterToUint(address); + var executeResult = Native.ProgrammerApi.Execute(uintAddress); - output = this.CheckResult(executeResult); + output = this.CheckResult(executeResult); + } } catch (Exception ex) { @@ -763,8 +709,12 @@ public CubeProgrammerError Execute(string address = "0x08000000") /// public CubeProgrammerError MassErase(string sFlashMemName = "") { - var massEraseResult = Native.ProgrammerApi.MassErase(sFlashMemName); - var output = this.CheckResult(massEraseResult); + var output = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var massEraseResult = Native.ProgrammerApi.MassErase(sFlashMemName); + output = this.CheckResult(massEraseResult); + } return output; } @@ -772,8 +722,12 @@ public CubeProgrammerError MassErase(string sFlashMemName = "") /// public CubeProgrammerError SectorErase(uint[] sectors, uint sectorNbr, string sFlashMemName = "") { - var sectorEraseResult = Native.ProgrammerApi.SectorErase(sectors, sectorNbr, sFlashMemName); - var output = this.CheckResult(sectorEraseResult); + var output = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var sectorEraseResult = Native.ProgrammerApi.SectorErase(sectors, sectorNbr, sFlashMemName); + output = this.CheckResult(sectorEraseResult); + } return output; } @@ -781,8 +735,12 @@ public CubeProgrammerError SectorErase(uint[] sectors, uint sectorNbr, string sF /// public CubeProgrammerError ReadUnprotect() { - var result = Native.ProgrammerApi.ReadUnprotect(); - var output = this.CheckResult(result); + var output = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var result = Native.ProgrammerApi.ReadUnprotect(); + output = this.CheckResult(result); + } return output; } @@ -790,8 +748,12 @@ public CubeProgrammerError ReadUnprotect() /// public CubeProgrammerError TzenRegression() { - var result = Native.ProgrammerApi.TzenRegression(); - var output = this.CheckResult(result); + var output = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var result = Native.ProgrammerApi.TzenRegression(); + output = this.CheckResult(result); + } return output; } @@ -799,20 +761,30 @@ public CubeProgrammerError TzenRegression() /// public TargetInterfaceType? GetTargetInterfaceType() { - var result = Native.ProgrammerApi.GetTargetInterfaceType(); - - if (result == -1) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - return null; + var result = Native.ProgrammerApi.GetTargetInterfaceType(); + + if (result == -1) + { + return null; + } + + return (TargetInterfaceType)result; } - return (TargetInterfaceType)result; + return null; } /// public int GetCancelPointer() { - return Native.ProgrammerApi.GetCancelPointer(); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + return Native.ProgrammerApi.GetCancelPointer(); + } + + return 0; } /// @@ -823,37 +795,40 @@ public int GetCancelPointer() if (!String.IsNullOrEmpty(filePath)) { var filePathAdapted = filePath.Replace(@"\", "/"); - - var filePointer = Native.ProgrammerApi.FileOpen(filePathAdapted); + var filePointer = IntPtr.Zero; try { - if (!filePointer.Equals(IntPtr.Zero)) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - var fileData = Marshal.PtrToStructure(filePointer); - deviceSegmentData.Type = fileData.Type; - deviceSegmentData.segmentsNbr = fileData.segmentsNbr; - deviceSegmentData.segments = new List(); - - if (fileData.segments != IntPtr.Zero) + filePointer = Native.ProgrammerApi.FileOpen(filePathAdapted); + if (!filePointer.Equals(IntPtr.Zero)) { - for (var i = 0; i < fileData.segmentsNbr; i++) + var fileData = Marshal.PtrToStructure(filePointer); + deviceSegmentData.Type = fileData.Type; + deviceSegmentData.segmentsNbr = fileData.segmentsNbr; + deviceSegmentData.segments = new List(); + + if (fileData.segments != IntPtr.Zero) { - var deviceSegment = new DeviceSegmentDataC(); - var segment = - Marshal.PtrToStructure(fileData.segments + (i * segmentSize)); - deviceSegment.address = segment.address; - deviceSegment.size = segment.size; - if (segment.data != IntPtr.Zero) + for (var i = 0; i < fileData.segmentsNbr; i++) { - deviceSegment.data = new byte[segment.size]; - Marshal.Copy(segment.data, deviceSegment.data, 0, segment.size); - } + var deviceSegment = new DeviceSegmentDataC(); + var segment = + Marshal.PtrToStructure(fileData.segments + (i * segmentSize)); + deviceSegment.address = segment.address; + deviceSegment.size = segment.size; + if (segment.data != IntPtr.Zero) + { + deviceSegment.data = new byte[segment.size]; + Marshal.Copy(segment.data, deviceSegment.data, 0, segment.size); + } - deviceSegmentData.segments.Add(deviceSegment); + deviceSegmentData.segments.Add(deviceSegment); + } } - } - return deviceSegmentData; + return deviceSegmentData; + } } } catch (Exception ex) @@ -878,9 +853,12 @@ public IntPtr FileOpenAsPointer(string filePath) { try { - var filePathAdapted = filePath.Replace(@"\", "/"); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var filePathAdapted = filePath.Replace(@"\", "/"); - return Native.ProgrammerApi.FileOpen(filePathAdapted); + return Native.ProgrammerApi.FileOpen(filePathAdapted); + } } catch (Exception ex) { @@ -893,28 +871,38 @@ public IntPtr FileOpenAsPointer(string filePath) /// public void FreeFileData(IntPtr data) { - if (data != IntPtr.Zero) - { - Native.ProgrammerApi.FreeFileData(data); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + if (data != IntPtr.Zero) + { + Native.ProgrammerApi.FreeFileData(data); + } } } /// public void FreeLibraryMemory(IntPtr ptr) { - if (ptr != IntPtr.Zero) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - Native.ProgrammerApi.FreeLibraryMemory(ptr); + if (ptr != IntPtr.Zero) + { + Native.ProgrammerApi.FreeLibraryMemory(ptr); + } } } /// public CubeProgrammerError Verify(IntPtr fileData, string address) { - var uintAddress = this.HexConverterToUint(address); + var output = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var uintAddress = this.HexConverterToUint(address); - var verifyResult = Native.ProgrammerApi.Verify(fileData, uintAddress); - var output = this.CheckResult(verifyResult); + var verifyResult = Native.ProgrammerApi.Verify(fileData, uintAddress); + output = this.CheckResult(verifyResult); + } return output; } @@ -923,19 +911,21 @@ public CubeProgrammerError Verify(IntPtr fileData, string address) public CubeProgrammerError VerifyMemory(string address, byte[] data) { var result = CubeProgrammerError.CubeprogrammerErrorOther; - - if (!String.IsNullOrEmpty(address) && data.Length > 0) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - var uintAddress = this.HexConverterToUint(address); + if (!String.IsNullOrEmpty(address) && data.Length > 0) + { + var uintAddress = this.HexConverterToUint(address); - var gch = GCHandle.Alloc(data, GCHandleType.Pinned); + var gch = GCHandle.Alloc(data, GCHandleType.Pinned); - var verifyMemoryResult = - Native.ProgrammerApi.VerifyMemory(uintAddress, gch.AddrOfPinnedObject(), (uint) data.Length); - gch.Free(); - result = this.CheckResult(verifyMemoryResult); + var verifyMemoryResult = + Native.ProgrammerApi.VerifyMemory(uintAddress, gch.AddrOfPinnedObject(), (uint)data.Length); + gch.Free(); + result = this.CheckResult(verifyMemoryResult); - return result; + return result; + } } return result; @@ -945,19 +935,21 @@ public CubeProgrammerError VerifyMemory(string address, byte[] data) public CubeProgrammerError VerifyMemoryBySegment(string address, byte[] data) { var result = CubeProgrammerError.CubeprogrammerErrorOther; - - if (!String.IsNullOrEmpty(address) && data.Length > 0) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - var uintAddress = this.HexConverterToUint(address); + if (!String.IsNullOrEmpty(address) && data.Length > 0) + { + var uintAddress = this.HexConverterToUint(address); - var gch = GCHandle.Alloc(data, GCHandleType.Pinned); + var gch = GCHandle.Alloc(data, GCHandleType.Pinned); - var verifyMemoryResult = - Native.ProgrammerApi.VerifyMemoryBySegment(uintAddress, gch.AddrOfPinnedObject(), (uint)data.Length); - gch.Free(); - result = this.CheckResult(verifyMemoryResult); + var verifyMemoryResult = + Native.ProgrammerApi.VerifyMemoryBySegment(uintAddress, gch.AddrOfPinnedObject(), (uint)data.Length); + gch.Free(); + result = this.CheckResult(verifyMemoryResult); - return result; + return result; + } } return result; @@ -976,8 +968,11 @@ public CubeProgrammerError SaveFileToFile(IntPtr fileData, string sFileName) try { - var saveFileToFileResult = Native.ProgrammerApi.SaveFileToFile(fileData, sFileNameAdapted); - output = this.CheckResult(saveFileToFileResult); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var saveFileToFileResult = Native.ProgrammerApi.SaveFileToFile(fileData, sFileNameAdapted); + output = this.CheckResult(saveFileToFileResult); + } } catch (Exception ex) { @@ -1002,10 +997,13 @@ public CubeProgrammerError SaveMemoryToFile(string address, string size, string try { - var saveMemoryToFileResult = + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var saveMemoryToFileResult = Native.ProgrammerApi.SaveMemoryToFile(intAddress, intSize, fileNameAdapted); - output = this.CheckResult(saveMemoryToFileResult); + output = this.CheckResult(saveMemoryToFileResult); + } } catch (Exception ex) { @@ -1018,30 +1016,40 @@ public CubeProgrammerError SaveMemoryToFile(string address, string size, string /// public CubeProgrammerError Disconnect() { - var result = Native.ProgrammerApi.Disconnect(); + var output = CubeProgrammerError.CubeprogrammerErrorOther; - var output = this.CheckResult(result); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var result = Native.ProgrammerApi.Disconnect(); + output = this.CheckResult(result); + } return output; } /// public void DeleteInterfaceList() { - Native.ProgrammerApi.DeleteInterfaceList(); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + Native.ProgrammerApi.DeleteInterfaceList(); + } } /// public void AutomaticMode(string filePath, string address, uint skipErase = 1U, uint verify = 1U, int isMassErase = 0, string obCommand = "", int run = 1) { - if (!String.IsNullOrEmpty(filePath)) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - var filePathAdapted = filePath.Replace(@"\", "/"); - if (!String.IsNullOrEmpty(address)) + if (!String.IsNullOrEmpty(filePath)) { - var uintAddress = this.HexConverterToUint(address); + var filePathAdapted = filePath.Replace(@"\", "/"); + if (!String.IsNullOrEmpty(address)) + { + var uintAddress = this.HexConverterToUint(address); - Native.ProgrammerApi.AutomaticMode(filePathAdapted, uintAddress, skipErase, verify, isMassErase, obCommand, run); + Native.ProgrammerApi.AutomaticMode(filePathAdapted, uintAddress, skipErase, verify, isMassErase, obCommand, run); + } } } } @@ -1049,14 +1057,17 @@ public void AutomaticMode(string filePath, string address, uint skipErase = 1U, /// public void SerialNumberingAutomaticMode(string filePath, string address, uint skipErase = 1U, uint verify = 1U, int isMassErase = 0, string obCommand = "", int run = 1, int enableSerialNumbering = 0, int serialAddress = 0, int serialSize = 0, string serialInitialData = "") { - if (!String.IsNullOrEmpty(filePath)) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - var filePathAdapted = filePath.Replace(@"\", "/"); - if (!String.IsNullOrEmpty(address)) + if (!String.IsNullOrEmpty(filePath)) { - var uintAddress = this.HexConverterToUint(address); + var filePathAdapted = filePath.Replace(@"\", "/"); + if (!String.IsNullOrEmpty(address)) + { + var uintAddress = this.HexConverterToUint(address); - Native.ProgrammerApi.SerialNumberingAutomaticMode(filePathAdapted, uintAddress, skipErase, verify, isMassErase, obCommand, run, enableSerialNumbering, serialAddress, serialSize, serialInitialData); + Native.ProgrammerApi.SerialNumberingAutomaticMode(filePathAdapted, uintAddress, skipErase, verify, isMassErase, obCommand, run, enableSerialNumbering, serialAddress, serialSize, serialInitialData); + } } } } @@ -1072,53 +1083,57 @@ public void SerialNumberingAutomaticMode(string filePath, string address, uint s var output = CubeProgrammerError.CubeprogrammerErrorOther; try { - var result = Native.ProgrammerApi.GetStorageStructure(ref storageStructurePtr); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var result = Native.ProgrammerApi.GetStorageStructure(ref storageStructurePtr); - output = this.CheckResult(result); + output = this.CheckResult(result); - if (output.Equals(CubeProgrammerError.CubeprogrammerNoError)) - { - if (storageStructurePtr != IntPtr.Zero) + if (output.Equals(CubeProgrammerError.CubeprogrammerNoError)) { - var storageStructure = Marshal.PtrToStructure(storageStructurePtr); - - deviceStorageStructure.BanksNumber = storageStructure.BanksNumber; - var deviceBankList = new List(); - for (var i = 0; i < storageStructure.BanksNumber; i++) + if (storageStructurePtr != IntPtr.Zero) { + var storageStructure = Marshal.PtrToStructure(storageStructurePtr); - if (storageStructure.Banks != IntPtr.Zero) + deviceStorageStructure.BanksNumber = storageStructure.BanksNumber; + var deviceBankList = new List(); + for (var i = 0; i < storageStructure.BanksNumber; i++) { - var deviceBank = Marshal.PtrToStructure(storageStructure.Banks + (i * deviceBankSize)); - var bankSectorList = new List(); - if (deviceBank.Sectors != IntPtr.Zero) + + if (storageStructure.Banks != IntPtr.Zero) { - for (var ii = 0; ii < deviceBank.SectorsNumber; ii++) + var deviceBank = Marshal.PtrToStructure(storageStructure.Banks + (i * deviceBankSize)); + var bankSectorList = new List(); + if (deviceBank.Sectors != IntPtr.Zero) { - var bankSector = - Marshal.PtrToStructure(deviceBank.Sectors + - (ii * bankSectorSize)); + for (var ii = 0; ii < deviceBank.SectorsNumber; ii++) + { + var bankSector = + Marshal.PtrToStructure(deviceBank.Sectors + + (ii * bankSectorSize)); - bankSectorList.Add(bankSector); + bankSectorList.Add(bankSector); - Marshal.DestroyStructure(deviceBank.Sectors + - (ii * bankSectorSize)); + Marshal.DestroyStructure(deviceBank.Sectors + + (ii * bankSectorSize)); + } } - } - var deviceDeviceBank = new DeviceDeviceBank - { - SectorsNumber = deviceBank.SectorsNumber, Sectors = bankSectorList - }; + var deviceDeviceBank = new DeviceDeviceBank + { + SectorsNumber = deviceBank.SectorsNumber, + Sectors = bankSectorList + }; - deviceBankList.Add(deviceDeviceBank); + deviceBankList.Add(deviceDeviceBank); - Marshal.DestroyStructure(storageStructure.Banks + (i * deviceBankSize)); + Marshal.DestroyStructure(storageStructure.Banks + (i * deviceBankSize)); + } } - } - deviceStorageStructure.Banks = deviceBankList; - Marshal.DestroyStructure(storageStructurePtr); + deviceStorageStructure.Banks = deviceBankList; + Marshal.DestroyStructure(storageStructurePtr); + } } } } @@ -1139,25 +1154,39 @@ public void SerialNumberingAutomaticMode(string filePath, string address, uint s /// public CubeProgrammerError SendOptionBytesCmd(string command) { - var result = Native.ProgrammerApi.SendOptionBytesCmd(command); - var output = this.CheckResult(result); + var output = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var result = Native.ProgrammerApi.SendOptionBytesCmd(command); + output = this.CheckResult(result); + } return output; } /// public DevicePeripheralC? InitOptionBytesInterface() { - var pointer = Native.ProgrammerApi.InitOptionBytesInterface(); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var pointer = Native.ProgrammerApi.InitOptionBytesInterface(); - return pointer != IntPtr.Zero ? this.DevicePeripheralCHandler(pointer) : null; + return pointer != IntPtr.Zero ? this.DevicePeripheralCHandler(pointer) : null; + } + + return null; } /// public DevicePeripheralC? FastRomInitOptionBytesInterface(ushort deviceId) { - var pointer = Native.ProgrammerApi.FastRomInitOptionBytesInterface(deviceId); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var pointer = Native.ProgrammerApi.FastRomInitOptionBytesInterface(deviceId); + + return pointer != IntPtr.Zero ? this.DevicePeripheralCHandler(pointer) : null; + } - return pointer != IntPtr.Zero ? this.DevicePeripheralCHandler(pointer) : null; + return null; } private DevicePeripheralC? DevicePeripheralCHandler(IntPtr pointer) @@ -1166,102 +1195,105 @@ public CubeProgrammerError SendOptionBytesCmd(string command) try { - PeripheralC? peripheralC = Marshal.PtrToStructure(pointer); - - var bankCList = new List(); - for (var i = 0; i < peripheralC.Value.BanksNbr; i++) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - if (peripheralC.Value.Banks != IntPtr.Zero) - { - var bankCItemPointer = Marshal.ReadIntPtr(peripheralC.Value.Banks + (i * pointerSize)); - var bankCItem = Marshal.PtrToStructure(bankCItemPointer); + PeripheralC? peripheralC = Marshal.PtrToStructure(pointer); - if (bankCItem.Categories != IntPtr.Zero) + var bankCList = new List(); + for (var i = 0; i < peripheralC.Value.BanksNbr; i++) + { + if (peripheralC.Value.Banks != IntPtr.Zero) { - var categoryCList = new List(); - for (var ii = 0; ii < bankCItem.CategoriesNbr; ii++) - { - var categoryCItemPointer = - Marshal.ReadIntPtr(bankCItem.Categories + (ii * pointerSize)); - var categoryCItem = Marshal.PtrToStructure(categoryCItemPointer); + var bankCItemPointer = Marshal.ReadIntPtr(peripheralC.Value.Banks + (i * pointerSize)); + var bankCItem = Marshal.PtrToStructure(bankCItemPointer); - if (categoryCItem.Bits != IntPtr.Zero) + if (bankCItem.Categories != IntPtr.Zero) + { + var categoryCList = new List(); + for (var ii = 0; ii < bankCItem.CategoriesNbr; ii++) { - var bitCList = new List(); - for (var iii = 0; iii < categoryCItem.BitsNbr; iii++) - { - var bitCItemPointer = - Marshal.ReadIntPtr(categoryCItem.Bits + (iii * pointerSize)); - var bitCItem = Marshal.PtrToStructure(bitCItemPointer); + var categoryCItemPointer = + Marshal.ReadIntPtr(bankCItem.Categories + (ii * pointerSize)); + var categoryCItem = Marshal.PtrToStructure(categoryCItemPointer); - if (bitCItem.Values != IntPtr.Zero) + if (categoryCItem.Bits != IntPtr.Zero) + { + var bitCList = new List(); + for (var iii = 0; iii < categoryCItem.BitsNbr; iii++) { - var bitValueCList = new List(); - for (var iiii = 0; iiii < bitCItem.ValuesNbr; iiii++) - { - var bitValueCItemPointer = - Marshal.ReadIntPtr(bitCItem.Values + (iiii * pointerSize)); - var bitValueCItem = - Marshal.PtrToStructure(bitValueCItemPointer); - bitValueCList.Add(bitValueCItem); - - Marshal.DestroyStructure(bitValueCItemPointer); - } + var bitCItemPointer = + Marshal.ReadIntPtr(categoryCItem.Bits + (iii * pointerSize)); + var bitCItem = Marshal.PtrToStructure(bitCItemPointer); - var deviceBitC = new DeviceBitC + if (bitCItem.Values != IntPtr.Zero) { - Name = bitCItem.Name, - Description = bitCItem.Description, - WordOffset = bitCItem.WordOffset, - BitOffset = bitCItem.BitOffset, - BitWidth = bitCItem.BitWidth, - Access = bitCItem.Access, - ValuesNbr = bitCItem.ValuesNbr, - Values = bitValueCList, - Equation = bitCItem.Equation, - Reference = bitCItem.Reference, - BitValue = bitCItem.BitValue - }; - bitCList.Add(deviceBitC); - - Marshal.DestroyStructure(bitCItemPointer); + var bitValueCList = new List(); + for (var iiii = 0; iiii < bitCItem.ValuesNbr; iiii++) + { + var bitValueCItemPointer = + Marshal.ReadIntPtr(bitCItem.Values + (iiii * pointerSize)); + var bitValueCItem = + Marshal.PtrToStructure(bitValueCItemPointer); + bitValueCList.Add(bitValueCItem); + + Marshal.DestroyStructure(bitValueCItemPointer); + } + + var deviceBitC = new DeviceBitC + { + Name = bitCItem.Name, + Description = bitCItem.Description, + WordOffset = bitCItem.WordOffset, + BitOffset = bitCItem.BitOffset, + BitWidth = bitCItem.BitWidth, + Access = bitCItem.Access, + ValuesNbr = bitCItem.ValuesNbr, + Values = bitValueCList, + Equation = bitCItem.Equation, + Reference = bitCItem.Reference, + BitValue = bitCItem.BitValue + }; + bitCList.Add(deviceBitC); + + Marshal.DestroyStructure(bitCItemPointer); + } } - } - var deviceCategoryC = new DeviceCategoryC - { - Name = categoryCItem.Name, - BitsNbr = categoryCItem.BitsNbr, - Bits = bitCList - }; - categoryCList.Add(deviceCategoryC); - Marshal.DestroyStructure(categoryCItemPointer); + var deviceCategoryC = new DeviceCategoryC + { + Name = categoryCItem.Name, + BitsNbr = categoryCItem.BitsNbr, + Bits = bitCList + }; + categoryCList.Add(deviceCategoryC); + Marshal.DestroyStructure(categoryCItemPointer); + } } - } - var deviceBankC = new DeviceBankC - { - Size = bankCItem.Size, - Address = bankCItem.Address, - Access = bankCItem.Access, - CategoriesNbr = bankCItem.CategoriesNbr, - Categories = categoryCList - }; - bankCList.Add(deviceBankC); - Marshal.DestroyStructure(bankCItemPointer); + var deviceBankC = new DeviceBankC + { + Size = bankCItem.Size, + Address = bankCItem.Address, + Access = bankCItem.Access, + CategoriesNbr = bankCItem.CategoriesNbr, + Categories = categoryCList + }; + bankCList.Add(deviceBankC); + Marshal.DestroyStructure(bankCItemPointer); + } } } - } - var devicePeripheralC = new DevicePeripheralC - { - Name = peripheralC.Value.Name, - Description = peripheralC.Value.Description, - BanksNbr = peripheralC.Value.BanksNbr, - Banks = bankCList - }; + var devicePeripheralC = new DevicePeripheralC + { + Name = peripheralC.Value.Name, + Description = peripheralC.Value.Description, + BanksNbr = peripheralC.Value.BanksNbr, + Banks = bankCList + }; - return devicePeripheralC; + return devicePeripheralC; + } } catch (Exception ex) { @@ -1278,13 +1310,16 @@ public CubeProgrammerError SendOptionBytesCmd(string command) /// public CubeProgrammerError ObDisplay() { - this._logger?.LogTrace("ObDisplay."); + //this._logger?.LogTrace("ObDisplay."); var output = CubeProgrammerError.CubeprogrammerErrorOther; try { - var obDisplayResult = Native.ProgrammerApi.ObDisplay(); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var obDisplayResult = Native.ProgrammerApi.ObDisplay(); - output = this.CheckResult(obDisplayResult); + output = this.CheckResult(obDisplayResult); + } } catch (Exception ex) { @@ -1303,8 +1338,11 @@ public CubeProgrammerError ObDisplay() /// public void SetLoadersPath(string path) { - var pathAdapted = path.Replace(@"\", "/"); - Native.ProgrammerApi.SetLoadersPath(pathAdapted); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var pathAdapted = path.Replace(@"\", "/"); + Native.ProgrammerApi.SetLoadersPath(pathAdapted); + } } /// @@ -1317,31 +1355,34 @@ public void SetLoadersPath(string path) try { - Native.ProgrammerApi.SetExternalLoaderPath(pathAdapted, ref externalLoaderPtr); - if (externalLoaderPtr != IntPtr.Zero) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - var externalLoaderStructure = Marshal.PtrToStructure(externalLoaderPtr); + Native.ProgrammerApi.SetExternalLoaderPath(pathAdapted, ref externalLoaderPtr); + if (externalLoaderPtr != IntPtr.Zero) + { + var externalLoaderStructure = Marshal.PtrToStructure(externalLoaderPtr); - output.filePath = externalLoaderStructure.filePath; - output.deviceName = externalLoaderStructure.deviceName; - output.deviceType = externalLoaderStructure.deviceType; - output.deviceStartAddress = externalLoaderStructure.deviceStartAddress; - output.deviceSize = externalLoaderStructure.deviceSize; - output.pageSize = externalLoaderStructure.pageSize; - output.sectorsTypeNbr = externalLoaderStructure.sectorsTypeNbr; + output.filePath = externalLoaderStructure.filePath; + output.deviceName = externalLoaderStructure.deviceName; + output.deviceType = externalLoaderStructure.deviceType; + output.deviceStartAddress = externalLoaderStructure.deviceStartAddress; + output.deviceSize = externalLoaderStructure.deviceSize; + output.pageSize = externalLoaderStructure.pageSize; + output.sectorsTypeNbr = externalLoaderStructure.sectorsTypeNbr; - if (externalLoaderStructure.sectors != IntPtr.Zero) - { - var deviceSectorList = new List(); - for (var i = 0; i < externalLoaderStructure.sectorsTypeNbr; i++) + if (externalLoaderStructure.sectors != IntPtr.Zero) { - var deviceSectorItem = Marshal.PtrToStructure(externalLoaderStructure.sectors + (i * deviceSectorSize)); - deviceSectorList.Add(deviceSectorItem); - } + var deviceSectorList = new List(); + for (var i = 0; i < externalLoaderStructure.sectorsTypeNbr; i++) + { + var deviceSectorItem = Marshal.PtrToStructure(externalLoaderStructure.sectors + (i * deviceSectorSize)); + deviceSectorList.Add(deviceSectorItem); + } - output.sectors = deviceSectorList; + output.sectors = deviceSectorList; - return output; + return output; + } } } } @@ -1363,31 +1404,34 @@ public void SetLoadersPath(string path) try { - Native.ProgrammerApi.SetExternalLoaderOBL(pathAdapted, ref externalLoaderPtr); - if (externalLoaderPtr != IntPtr.Zero) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - var externalLoaderStructure = Marshal.PtrToStructure(externalLoaderPtr); + Native.ProgrammerApi.SetExternalLoaderOBL(pathAdapted, ref externalLoaderPtr); + if (externalLoaderPtr != IntPtr.Zero) + { + var externalLoaderStructure = Marshal.PtrToStructure(externalLoaderPtr); - output.filePath = externalLoaderStructure.filePath; - output.deviceName = externalLoaderStructure.deviceName; - output.deviceType = externalLoaderStructure.deviceType; - output.deviceStartAddress = externalLoaderStructure.deviceStartAddress; - output.deviceSize = externalLoaderStructure.deviceSize; - output.pageSize = externalLoaderStructure.pageSize; - output.sectorsTypeNbr = externalLoaderStructure.sectorsTypeNbr; + output.filePath = externalLoaderStructure.filePath; + output.deviceName = externalLoaderStructure.deviceName; + output.deviceType = externalLoaderStructure.deviceType; + output.deviceStartAddress = externalLoaderStructure.deviceStartAddress; + output.deviceSize = externalLoaderStructure.deviceSize; + output.pageSize = externalLoaderStructure.pageSize; + output.sectorsTypeNbr = externalLoaderStructure.sectorsTypeNbr; - if (externalLoaderStructure.sectors != IntPtr.Zero) - { - var deviceSectorList = new List(); - for (var i = 0; i < externalLoaderStructure.sectorsTypeNbr; i++) + if (externalLoaderStructure.sectors != IntPtr.Zero) { - var deviceSectorItem = Marshal.PtrToStructure(externalLoaderStructure.sectors + (i * deviceSectorSize)); - deviceSectorList.Add(deviceSectorItem); - } + var deviceSectorList = new List(); + for (var i = 0; i < externalLoaderStructure.sectorsTypeNbr; i++) + { + var deviceSectorItem = Marshal.PtrToStructure(externalLoaderStructure.sectors + (i * deviceSectorSize)); + deviceSectorList.Add(deviceSectorItem); + } - output.sectors = deviceSectorList; + output.sectors = deviceSectorList; - return output; + return output; + } } } } @@ -1410,49 +1454,52 @@ public void SetLoadersPath(string path) try { - var result = Native.ProgrammerApi.GetExternalLoaders(pathAdapted, ref externalStorageInfoPtr); - if (result.Equals(0)) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - var externalLoaderSize = Marshal.SizeOf(); - var externalStorageInfoStructure = Marshal.PtrToStructure(externalStorageInfoPtr); + var result = Native.ProgrammerApi.GetExternalLoaders(pathAdapted, ref externalStorageInfoPtr); + if (result.Equals(0)) + { + var externalLoaderSize = Marshal.SizeOf(); + var externalStorageInfoStructure = Marshal.PtrToStructure(externalStorageInfoPtr); - output.ExternalLoaderNbr = externalStorageInfoStructure.ExternalLoaderNbr; + output.ExternalLoaderNbr = externalStorageInfoStructure.ExternalLoaderNbr; - if (externalStorageInfoStructure.ExternalLoader != IntPtr.Zero) - { - for (var i = 0; i < externalStorageInfoStructure.ExternalLoaderNbr; i++) + if (externalStorageInfoStructure.ExternalLoader != IntPtr.Zero) { - var externalLoaderStructure = Marshal.PtrToStructure(externalStorageInfoStructure.ExternalLoader + (i * externalLoaderSize)); - - var deviceExternalLoader = new DeviceExternalLoader + for (var i = 0; i < externalStorageInfoStructure.ExternalLoaderNbr; i++) { - filePath = externalLoaderStructure.filePath, - deviceName = externalLoaderStructure.deviceName, - deviceType = externalLoaderStructure.deviceType, - deviceStartAddress = externalLoaderStructure.deviceStartAddress, - deviceSize = externalLoaderStructure.deviceSize, - pageSize = externalLoaderStructure.pageSize, - sectorsTypeNbr = externalLoaderStructure.sectorsTypeNbr - }; - - if (externalLoaderStructure.sectors != IntPtr.Zero) - { - var deviceSectorList = new List(); - for (var ii = 0; ii < externalLoaderStructure.sectorsTypeNbr; ii++) + var externalLoaderStructure = Marshal.PtrToStructure(externalStorageInfoStructure.ExternalLoader + (i * externalLoaderSize)); + + var deviceExternalLoader = new DeviceExternalLoader + { + filePath = externalLoaderStructure.filePath, + deviceName = externalLoaderStructure.deviceName, + deviceType = externalLoaderStructure.deviceType, + deviceStartAddress = externalLoaderStructure.deviceStartAddress, + deviceSize = externalLoaderStructure.deviceSize, + pageSize = externalLoaderStructure.pageSize, + sectorsTypeNbr = externalLoaderStructure.sectorsTypeNbr + }; + + if (externalLoaderStructure.sectors != IntPtr.Zero) { - var deviceSectorItem = Marshal.PtrToStructure(externalLoaderStructure.sectors + (ii * deviceSectorSize)); - deviceSectorList.Add(deviceSectorItem); + var deviceSectorList = new List(); + for (var ii = 0; ii < externalLoaderStructure.sectorsTypeNbr; ii++) + { + var deviceSectorItem = Marshal.PtrToStructure(externalLoaderStructure.sectors + (ii * deviceSectorSize)); + deviceSectorList.Add(deviceSectorItem); + } + + deviceExternalLoader.sectors = deviceSectorList; } - deviceExternalLoader.sectors = deviceSectorList; + externalLoaderList.Add(deviceExternalLoader); } - externalLoaderList.Add(deviceExternalLoader); - } - - output.ExternalLoader = externalLoaderList; + output.ExternalLoader = externalLoaderList; - return output; + return output; + } } } } @@ -1467,14 +1514,20 @@ public void SetLoadersPath(string path) /// public void RemoveExternalLoader(string path) { - var pathAdapted = path.Replace(@"\", "/"); - Native.ProgrammerApi.RemoveExternalLoader(pathAdapted); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var pathAdapted = path.Replace(@"\", "/"); + Native.ProgrammerApi.RemoveExternalLoader(pathAdapted); + } } /// public void DeleteLoaders() { - Native.ProgrammerApi.DeleteLoaders(); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + Native.ProgrammerApi.DeleteLoaders(); + } } #endregion @@ -1490,13 +1543,17 @@ public void DeleteLoaders() { var buffer = new byte[8]; var bufferPtr = new IntPtr(); + var result = CubeProgrammerError.CubeprogrammerErrorOther; - var getUID64Result = Native.ProgrammerApi.GetUID64(ref bufferPtr ); - - var result = this.CheckResult(getUID64Result); - if (result.Equals(CubeProgrammerError.CubeprogrammerNoError) && bufferPtr != IntPtr.Zero) + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) { - Marshal.Copy(bufferPtr, buffer, 0, 8); + var getUID64Result = Native.ProgrammerApi.GetUID64(ref bufferPtr); + + result = this.CheckResult(getUID64Result); + if (result.Equals(CubeProgrammerError.CubeprogrammerNoError) && bufferPtr != IntPtr.Zero) + { + Marshal.Copy(bufferPtr, buffer, 0, 8); + } } return (result, buffer); @@ -1505,9 +1562,13 @@ public void DeleteLoaders() /// public CubeProgrammerError FirmwareDelete() { - var firmwareDeleteResult = Native.ProgrammerApi.FirmwareDelete(); + var result = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var firmwareDeleteResult = Native.ProgrammerApi.FirmwareDelete(); - var result = this.CheckResult(firmwareDeleteResult); + result = this.CheckResult(firmwareDeleteResult); + } return result; } @@ -1517,11 +1578,14 @@ public CubeProgrammerError FirmwareUpgrade(string filePath, string address, uint { var uintAddress = this.HexConverterToUint(address); var filePathAdapted = String.IsNullOrEmpty(filePath) ? "" : filePath.Replace(@"\", "/"); - - var firmwareUpgradeResult = + var result = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var firmwareUpgradeResult = Native.ProgrammerApi.FirmwareUpgrade(filePathAdapted, uintAddress, firstInstall, startStack, verify); - var result = this.CheckResult(firmwareUpgradeResult); + result = this.CheckResult(firmwareUpgradeResult); + } return result; } @@ -1529,9 +1593,13 @@ public CubeProgrammerError FirmwareUpgrade(string filePath, string address, uint /// public CubeProgrammerError StartWirelessStack() { - var startWirelessStackResult = Native.ProgrammerApi.StartWirelessStack(); + var result = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var startWirelessStackResult = Native.ProgrammerApi.StartWirelessStack(); - var result = this.CheckResult(startWirelessStackResult); + result = this.CheckResult(startWirelessStackResult); + } return result; } @@ -1539,9 +1607,13 @@ public CubeProgrammerError StartWirelessStack() /// public CubeProgrammerError UpdateAuthKey(string filePath) { - var updateAuthKeyResult = Native.ProgrammerApi.UpdateAuthKey(filePath); + var result = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var updateAuthKeyResult = Native.ProgrammerApi.UpdateAuthKey(filePath); - var result = this.CheckResult(updateAuthKeyResult); + result = this.CheckResult(updateAuthKeyResult); + } return result; } @@ -1549,9 +1621,13 @@ public CubeProgrammerError UpdateAuthKey(string filePath) /// public CubeProgrammerError AuthKeyLock() { - var authKeyLockResult = Native.ProgrammerApi.AuthKeyLock(); + var result = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var authKeyLockResult = Native.ProgrammerApi.AuthKeyLock(); - var result = this.CheckResult(authKeyLockResult); + result = this.CheckResult(authKeyLockResult); + } return result; } @@ -1559,11 +1635,15 @@ public CubeProgrammerError AuthKeyLock() /// public CubeProgrammerError WriteUserKey(string filePath, byte keyType) { - var filePathAdapted = String.IsNullOrEmpty(filePath) ? "" : filePath.Replace(@"\", "/"); + var result = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var filePathAdapted = String.IsNullOrEmpty(filePath) ? "" : filePath.Replace(@"\", "/"); - var writeUserKeyResult = Native.ProgrammerApi.WriteUserKey(filePathAdapted, keyType); + var writeUserKeyResult = Native.ProgrammerApi.WriteUserKey(filePathAdapted, keyType); - var result = this.CheckResult(writeUserKeyResult); + result = this.CheckResult(writeUserKeyResult); + } return result; } @@ -1571,9 +1651,13 @@ public CubeProgrammerError WriteUserKey(string filePath, byte keyType) /// public CubeProgrammerError AntiRollBack() { - var antiRollBackResult = Native.ProgrammerApi.AntiRollBack(); + var result = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var antiRollBackResult = Native.ProgrammerApi.AntiRollBack(); - var result = this.CheckResult(antiRollBackResult); + result = this.CheckResult(antiRollBackResult); + } return result; } @@ -1581,9 +1665,13 @@ public CubeProgrammerError AntiRollBack() /// public CubeProgrammerError StartFus() { - var startFusResult = Native.ProgrammerApi.StartFus(); + var result = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var startFusResult = Native.ProgrammerApi.StartFus(); - var result = this.CheckResult(startFusResult); + result = this.CheckResult(startFusResult); + } return result; } @@ -1591,9 +1679,13 @@ public CubeProgrammerError StartFus() /// public CubeProgrammerError UnlockChip() { - var unlockChipResult = Native.ProgrammerApi.UnlockChip(); + var result = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var unlockChipResult = Native.ProgrammerApi.UnlockChip(); - var result = this.CheckResult(unlockChipResult); + result = this.CheckResult(unlockChipResult); + } return result; } @@ -1605,12 +1697,16 @@ public CubeProgrammerError UnlockChip() /// public CubeProgrammerError ProgramSsp(string sspFile, string licenseFile, string tfaFile, int hsmSlotId) { - var sspFileAdapted = String.IsNullOrEmpty(sspFile) ? "" : sspFile.Replace(@"\", "/"); - var licenseFileAdapted = String.IsNullOrEmpty(licenseFile) ? "" : licenseFile.Replace(@"\", "/"); - var tfaFileAdapted = String.IsNullOrEmpty(tfaFile) ? "" : tfaFile.Replace(@"\", "/"); - var programSspResult = Native.ProgrammerApi.ProgramSsp(sspFileAdapted, licenseFileAdapted, tfaFileAdapted, hsmSlotId); + var result = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var sspFileAdapted = String.IsNullOrEmpty(sspFile) ? "" : sspFile.Replace(@"\", "/"); + var licenseFileAdapted = String.IsNullOrEmpty(licenseFile) ? "" : licenseFile.Replace(@"\", "/"); + var tfaFileAdapted = String.IsNullOrEmpty(tfaFile) ? "" : tfaFile.Replace(@"\", "/"); + var programSspResult = Native.ProgrammerApi.ProgramSsp(sspFileAdapted, licenseFileAdapted, tfaFileAdapted, hsmSlotId); - var result = this.CheckResult(programSspResult); + result = this.CheckResult(programSspResult); + } return result; } @@ -1622,40 +1718,65 @@ public CubeProgrammerError ProgramSsp(string sspFile, string licenseFile, string /// public string GetHsmFirmwareID(int hsmSlotId) { - return Native.ProgrammerApi.GetHsmFirmwareID(hsmSlotId); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + return Native.ProgrammerApi.GetHsmFirmwareID(hsmSlotId); + } + + return String.Empty; } /// public ulong GetHsmCounter(int hsmSlotId) { - return Native.ProgrammerApi.GetHsmCounter(hsmSlotId); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + return Native.ProgrammerApi.GetHsmCounter(hsmSlotId); + } + return 0UL; } /// public string GetHsmState(int hsmSlotId) { - return Native.ProgrammerApi.GetHsmState(hsmSlotId); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + return Native.ProgrammerApi.GetHsmState(hsmSlotId); + } + return String.Empty; } /// public string GetHsmVersion(int hsmSlotId) { - return Native.ProgrammerApi.GetHsmVersion(hsmSlotId); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + return Native.ProgrammerApi.GetHsmVersion(hsmSlotId); + } + return String.Empty; } /// public string GetHsmType(int hsmSlotId) { - return Native.ProgrammerApi.GetHsmType(hsmSlotId); + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + return Native.ProgrammerApi.GetHsmType(hsmSlotId); + } + return String.Empty; } /// public CubeProgrammerError GetHsmLicense(int hsmSlotId, string outLicensePath) { - var outLicensePathAdapted = String.IsNullOrEmpty(outLicensePath) ? "" : outLicensePath.Replace(@"\", "/"); - var getHsmLicenseResult = Native.ProgrammerApi.GetHsmLicense(hsmSlotId, outLicensePathAdapted); + var result = CubeProgrammerError.CubeprogrammerErrorOther; + if (Native.ProgrammerApi.EnsureNativeLibraryLoaded()) + { + var outLicensePathAdapted = String.IsNullOrEmpty(outLicensePath) ? "" : outLicensePath.Replace(@"\", "/"); + var getHsmLicenseResult = Native.ProgrammerApi.GetHsmLicense(hsmSlotId, outLicensePathAdapted); - var result = this.CheckResult(getHsmLicenseResult); + result = this.CheckResult(getHsmLicenseResult); + } return result; } @@ -1762,11 +1883,17 @@ protected void Dispose(bool disposing) } // Free any unmanaged objects here. - this._handleProgrammer?.Dispose(); - this._handleProgrammer = null; + if (Native.ProgrammerApi.HandleProgrammer != null) + { + Native.ProgrammerApi.HandleProgrammer?.Dispose(); + Native.ProgrammerApi.HandleProgrammer = null; + } - this._handleSTLinkDriver?.Dispose(); - this._handleSTLinkDriver = null; + if (Native.ProgrammerApi.HandleSTLinkDriver != null) + { + Native.ProgrammerApi.HandleSTLinkDriver?.Dispose(); + Native.ProgrammerApi.HandleSTLinkDriver = null; + } } /// diff --git a/src/01/KSociety.SharpCubeProgrammer/Native/ProgrammerApi.cs b/src/01/KSociety.SharpCubeProgrammer/Native/ProgrammerApi.cs index 4cec93a..1df67df 100644 --- a/src/01/KSociety.SharpCubeProgrammer/Native/ProgrammerApi.cs +++ b/src/01/KSociety.SharpCubeProgrammer/Native/ProgrammerApi.cs @@ -3,14 +3,175 @@ namespace SharpCubeProgrammer.Native { using System; + using System.IO; + using System.Reflection; using System.Runtime.InteropServices; using Enum; using Struct; internal static class ProgrammerApi { + /// + /// Synchronization object to protect loading the native library and its functions. This field is read-only. + /// + private static readonly object SyncRoot = new object(); + + internal static SafeLibraryHandle HandleSTLinkDriver; + internal static SafeLibraryHandle HandleProgrammer; + + internal static DisplayCallBacks DisplayCallBacks = new DisplayCallBacks(); + private const string ProgrammerDll = @"Programmer.dll"; + internal static bool EnsureNativeLibraryLoaded() + { + if (HandleSTLinkDriver == null || HandleProgrammer == null) + { + var currentDirectory = GetAssemblyDirectory(); + var target = Path.Combine(currentDirectory, "dll", Environment.Is64BitProcess ? "x64" : "x86"); + + try + { + var stLinkDriverResult = LoadStLinkDriver(target); + + if (stLinkDriverResult != null) + { + var programmerResult = LoadProgrammer(target); + + if (programmerResult != null) + { + return true; + } + else + { + return false; + } + } + else + { + return false; + } + }catch(Exception ex) + { + throw new Exception("K-Society CubeProgrammer native library loading error!", ex); + } + } + + return true; + } + + private static SafeLibraryHandle LoadStLinkDriver(string target) + { + if (HandleSTLinkDriver == null) + { + lock (SyncRoot) + { + if (HandleSTLinkDriver == null) + { +#if NET + if (!NativeLibrary.TryLoad( + target + @"\STLinkUSBDriver.dll", + typeof(CubeProgrammerApi).Assembly, + DllImportSearchPath.UserDirectories, + out IntPtr handle)) + { + var error = Marshal.GetLastWin32Error(); + HandleSTLinkDriver = null; + + throw new Exception("K-Society CubeProgrammer StLinkDriver loading error: " + error); + } + else + { + HandleSTLinkDriver = new Native.SafeLibraryHandle(handle); + } +#else + // Check if the local machine has KB2533623 installed in order + // to use the more secure flags when calling LoadLibraryEx + bool hasKB2533623; + + using (var hModule = Native.Utility.LoadLibraryEx(Native.Utility.KernelLibName, IntPtr.Zero, 0)) + { + // If the AddDllDirectory function is found then the flags are supported + hasKB2533623 = Native.Utility.GetProcAddress(hModule, "AddDllDirectory") != IntPtr.Zero; + } + + var dwFlags = 0; + + if (hasKB2533623) + { + // If KB2533623 is installed then specify the more secure LOAD_LIBRARY_SEARCH_DEFAULT_DIRS in dwFlags + dwFlags = Native.Utility.LOAD_LIBRARY_SEARCH_DEFAULT_DIRS; + } + + HandleSTLinkDriver = Native.Utility.LoadLibraryEx(target + @"\STLinkUSBDriver.dll", IntPtr.Zero, dwFlags); + + if (HandleSTLinkDriver.IsInvalid) + { + var error = Marshal.GetLastWin32Error(); + HandleSTLinkDriver = null; + + throw new Exception("K-Society CubeProgrammer StLinkDriver loading error: " + error); + } +#endif + } + } + } + + return HandleSTLinkDriver; + } + + private static SafeLibraryHandle LoadProgrammer(string target) + { + if (HandleProgrammer == null) + { + lock (SyncRoot) + { + if (HandleProgrammer == null) + { +#if NET + if (!NativeLibrary.TryLoad( + target + @"\Programmer.dll", + typeof(CubeProgrammerApi).Assembly, + DllImportSearchPath.UserDirectories, + out IntPtr handle)) + { + var error = Marshal.GetLastWin32Error(); + HandleProgrammer = null; + + throw new Exception("K-Society CubeProgrammer Programmer loading error: " + error); + } + else + { + HandleProgrammer = new Native.SafeLibraryHandle(handle); + } +#else + var dwFlags = Native.Utility.LOAD_WITH_ALTERED_SEARCH_PATH; + + HandleProgrammer = Native.Utility.LoadLibraryEx(target + @"\Programmer.dll", IntPtr.Zero, dwFlags); + + if (HandleProgrammer.IsInvalid) + { + var error = Marshal.GetLastWin32Error(); + HandleProgrammer = null; + + throw new Exception("K-Society CubeProgrammer Programmer loading error: " + error); + } +#endif + } + } + } + + return HandleProgrammer; + } + + private static string GetAssemblyDirectory() + { + var codeBase = Assembly.GetExecutingAssembly().Location; + var uri = new UriBuilder(codeBase); + var path = Uri.UnescapeDataString(uri.Path); + return Path.GetDirectoryName(path); + } + #region [STLINK] #region [TryConnectStLink]