Wrapper a dll from some link on the internet - c#

I am trying to wrapper a dll that are in some cloud directory.
private SafeLibraryHandle sevenZipSafeHandle;
public SevenZipHandle(string sevenZipLibPath)
{
this.sevenZipSafeHandle = Kernel32Dll.LoadLibrary(sevenZipLibPath);
if (this.sevenZipSafeHandle.IsInvalid)
{
throw new Win32Exception();
}
}
}
internal static class Kernel32Dll
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern SafeLibraryHandle LoadLibrary([MarshalAs(UnmanagedType.LPTStr)] string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern IntPtr GetProcAddress(SafeLibraryHandle hModule, [MarshalAs(UnmanagedType.LPStr)] string procName);
[SuppressUnmanagedCodeSecurity]
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FreeLibrary(IntPtr hModule);
}
I am validating a dll file, but if I use :
sevenZipLibPath = “c:/temp/file.dll”
it works fine.
But if use some file that is on the internet like:
sevenZipLibPath = “"http://any.blob.core.windows.net/files/file.dll”
it does not work.
How can I check a DLL file from some cloud drive in that situation?

The LoadLibrary function
https://msdn.microsoft.com/en-us/library/windows/desktop/ms684175(v=vs.85).aspx
Only supports filepaths, not urls.
So download it first to a temporary location. You can also do that in code using the webclient class.
A simple example:
https://stackoverflow.com/a/525372/4640588
Edit - Example using the paths you provided
using (WebClient client = new WebClient())
{
client.DownloadFile(
"http://any.blob.core.windows.net/files/file.dll",
"c:/temp/file.dll");
}
Validate it, then delete it afterwards.

Related

Attach console to process

I want to attach a console to an monogame application. I used .Net Framework at first and everything worked fine, then I switched to .Net Core 3.1 and the console stopped attaching to the process.
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AttachConsole(int dwProcessId);
[DllImportAttribute("kernel32.dll", SetLastError = true, EntryPoint = "AllocConsole")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
private static extern bool AllocConsole();
[DllImportAttribute("kernel32.dll", SetLastError = true, EntryPoint = "GetStdHandle")]
private static extern IntPtr GetStdHandle(Int32 nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FreeConsole();
[DllImport("kernel32.dll", EntryPoint = "GetLastError")]
private static extern int GetLastError();
private void InitializeConsole() {
if (AttachConsole(Process.GetCurrentProcess().Id) && AllocConsole()) {
GetStdHandle(Process.GetCurrentProcess().Id);
_isInitializeConsole = true;
} else {
_isInitializeConsole = false;
throw new Exception($"Console alloc error code: {GetLastError()}");
}
}
When trying to attach a console from the AttachConsole method, I get result "false" and last error code - 5 (Access is denied). I ran the application as administrator and getting error code - 6 (The handle is invalid).
Is there a way to fix this error?

Automatically set security attributes when moving files with Win32 API ? (C#)

I'm currently developing an app that have to move a file to another application folder. But the other application must have a specific permissions on files that are copied.
When I use the Win32 API to MoveFileFromApp (it's uwp app), it doesn't update the security attributes to inherit the folder.
here is the code of MoveFile (C#)
[DllImport("api-ms-win-core-file-fromapp-l1-1-0.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
internal static extern bool MoveFileFromApp(
string lpExistingFileName, string lpNewFileName);
Does anyone know how to set these security permissions for the folder automatically during the moving process ?
Thank you very much !
I tried to use SetNamedSecurityInfo method by P/Invoke in UWP app with the following code. The error ERROR_ACCESS_DENIED(error code is 5) always exists in UWP app. But in Win32, the usage of SetNamedSecurityInfo method with the value UNPROTECTED_DACL_SECURITY_INFORMATION to inherit the security attributes is successful.
In UWP, there are some limitations on file system access permission. Though the SetNamedSecurityInfo method can be called successfully, it does not work as expected.
The code to use SetNamedSecurityInfo method in UWP:
public uint DACL_SECURITY_INFORMATION = 0x00000004;
public uint UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000;
public uint ACL_REVISION = 0x2;
[StructLayout(LayoutKind.Sequential)]
public struct ACL
{
public byte AclRevision;
public byte Sbz1;
public ushort AclSize;
public ushort AceCount;
public ushort Sbz2;
}
public enum SE_OBJECT_TYPE
{
SE_UNKNOWN_OBJECT_TYPE = 0,
SE_FILE_OBJECT,
SE_SERVICE,
SE_PRINTER,
SE_REGISTRY_KEY,
SE_LMSHARE,
SE_KERNEL_OBJECT,
SE_WINDOW_OBJECT,
SE_DS_OBJECT,
SE_DS_OBJECT_ALL,
SE_PROVIDER_DEFINED_OBJECT,
SE_WMIGUID_OBJECT,
SE_REGISTRY_WOW64_32KEY,
SE_REGISTRY_WOW64_64KEY,
}
[DllImport("api-ms-win-core-file-fromapp-l1-1-0.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool MoveFileFromAppW(
string lpExistingFileName,
string lpNewFileName);
[DllImport("advapi32.DLL", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern uint SetNamedSecurityInfo(
string lpFileName,
SE_OBJECT_TYPE ObjectType,
uint SecurityInfo,
IntPtr psidOwner,
IntPtr psidGroup,
ref ACL pDacl,
IntPtr pSacl);
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern bool InitializeAcl(ref ACL pAcl, int nAclLength, uint dwAclRevision);
[DllImport("api-ms-win-core-file-fromapp-l1-1-0.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall,
SetLastError = true)]
internal static extern bool MoveFileFromApp(
string lpExistingFileName,
string lpNewFileName
);
public void SetFilePermission(string FileName)
{//Use the method to let the file inherit the security attributes from parent object
bool ret = false;
ACL pDacl = new ACL();
ret = InitializeAcl(ref pDacl, Marshal.SizeOf<ACL>(), ACL_REVISION);
uint SecurityInfo = DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION;
uint err = SetNamedSecurityInfo(FileName, SE_OBJECT_TYPE.SE_FILE_OBJECT, SecurityInfo, IntPtr.Zero, IntPtr.Zero, ref pDacl, IntPtr.Zero);
}

FindNextFile ERROR_INVALID_NAME

I'm trying to use the WINAPI functions FindFirstFile and FindNextFile.
However, I'm experiencing some issues.
When I first call the function FindFirstFile it works fine. I've got a valid handler and the first folder/file name is properly populated inside the WIN32_FIND_DATA structure. No error is found with GetLastError.
Then, I call FindNextFile which returns true as there are more folders in the directory I'm scanning. But I can't retrieve the next folder/file name and GetLastError returns 123 (0x7B) ERROR_INVALID_NAME.
I'm a little confused as it says in the official documentation that if an error occurs it should return 0.
https://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx
Return value
If the function succeeds, the return value is nonzero and the lpFindFileData parameter contains information about the next file or directory found.
If the function fails, the return value is zero and the contents of lpFindFileData are indeterminate. To get extended error information, call the GetLastError function.
If the function fails because no more matching files can be found, the GetLastError function returns ERROR_NO_MORE_FILES.
I'm using .NET 4.5.1 and Visual Studio 2013 on Windows 7 x64.
Here is a sample code.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct WIN32_FIND_DATA
{
public uint dwFileAttributes;
public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
public uint nFileSizeHigh;
public uint nFileSizeLow;
public uint dwReserved0;
public uint dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
...
[DllImport("Kernel32.dll", EntryPoint = "FindFirstFile", SetLastError = true)]
public static extern IntPtr FindFirstFile(string lpFileName, ref WIN32_FIND_DATA lpFindFileData);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("Kernel32.dll", EntryPoint = "FindFirstFile", SetLastError = true)]
public static extern bool FindNextFile(IntPtr hFindFile, ref WIN32_FIND_DATA lpFindFileData);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("Kernel32.dll", EntryPoint = "FindClose", SetLastError = true)]
public static extern bool FindClose(IntPtr hFindFile);
...
public static void Test()
{
WIN32_FIND_DATA metaDataFile = new WIN32_FIND_DATA();
IntPtr nextHandle = FileScanner.FindFirstFile("C:\\*", ref metaDataFile);
Console.WriteLine(Marshal.GetLastWin32Error()); // This equals 0x0 ERROR_SUCCESS
Console.WriteLine(metaDataFile.cFileName); // This equals $Recycle.Bin
/* Check invalid handler */
if (nextHandle != new IntPtr(-1L))
{
bool moreFiles = true;
while (moreFiles)
{
moreFiles = FileScanner.FindNextFile(nextHandle, ref metaDataFile);
Console.WriteLine(Marshal.GetLastWin32Error()); // This equals 0x7B ERROR_INVALID_NAME
Console.WriteLine(metaDataFile.cFileName); // This equals $Recycle.Bin and this value never change.
}
FindClose(nextHandle);
}
}
For some reason, moreFiles is always true and GetLastError returns ERROR_INVALID_NAME ...
If you need any details please ask me.
Any help would really be appreciated !
Only call Marshal.GetLastWin32Error is the API call reports failure. In the case of FindNextFile it does so by returning false. You are checking the value returned by Marshal.GetLastWin32Error indiscriminately.
The documentation makes this clear when it tells you how the functions indicate failure. You even linked the text. But you said:
I'm a little confused as it says in the official documentation that if an error occurs it should return 0.
That's right. So check the return value against 0. In the case of a BOOL marshalled as C# bool, that means that the function returns false if it fails. But you simply ignored the return value and tested the value returned by Marshal.GetLastWin32Error(), something altogether different.
The code should be more like this:
public static void Test()
{
WIN32_FIND_DATA fd = new WIN32_FIND_DATA();
IntPtr findHandle = FileScanner.FindFirstFile("C:\\*", ref fd);
if (findHandle == INVALID_HANDLE_VALUE)
throw new Win32Exception();
do
{
Console.WriteLine(fd.cFileName);
} while (FileScanner.FindNextFile(findHandle, ref fd));
// you might check that Marshal.GetLastWin32Error() returns ERROR_NO_MORE_FILES
// at this point, otherwise the enumeration failed abnormally
if (!FindClose(findHandle))
throw new Win32Exception();
}
Your other problem, and it's what hurting you most, is your p/invoke declarations. Look closely at this one:
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("Kernel32.dll", EntryPoint = "FindFirstFile", SetLastError = true)]
public static extern bool FindNextFile(IntPtr hFindFile,
ref WIN32_FIND_DATA lpFindFileData);
The EntryPoint is not correct. So you are actually calling FindFirstFile instead of FindNextFile and it's hardly surprising that fails.
Specifying the EntryPoint when you don't need to is simply asking for trouble. And you've fallen right into the trap. I'd declare these imports like so:
[DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr FindFirstFile(string lpFileName,
ref WIN32_FIND_DATA lpFindFileData);
[DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool FindNextFile(IntPtr hFindFile,
ref WIN32_FIND_DATA lpFindFileData);
[DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool FindClose(IntPtr hFindFile);
Note that there's no need for the return attribute since UnmanagedType.Bool is the default.
And then you'd need to change the CharSet on the struct to be CharSet.Unicode to match. There's no point at all in opting for ANSI here.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WIN32_FIND_DATA
{
....
}
Finally, all of this code seems to me to be pointless. What's wrong with Directory.EnumerateFiles and Directory.EnumerateDirectories?

Error using c DLL. Attempted to read or write protected memory

I try use a dll created in c in c#, but I get the error "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
I see very topics here, but i'm not solve the problem. It's possible help me?
My C# code is:
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32")]
public static extern bool FreeLibrary(IntPtr hModule);
[DllImport("lib.dll", EntryPoint = "LoadRes", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern SRes LoadRes([MarshalAs(UnmanagedType.LPStr)]string str, bool type);
SRes sres = new SRes();
string path="C:\\123456.fil";
System.IntPtr load = LoadLibrary("lib.dll");
System.IntPtr adress = GetProcAddress(load, "LoadRes");
sres = LoadRes(path, true);
My code to export in c is
__declspec(dllexport) SRes LoadRes( const char *filename, bool header_only );
Thank's for help!!

How to dynamically load and unload a native DLL file?

I have a buggy third-party DLL files that, after some time of execution, starts throwing the access violation exceptions. When that happens I want to reload that DLL file. How do I do that?
Try this
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr LoadLibrary(string libname);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool FreeLibrary(IntPtr hModule);
//Load
IntPtr Handle = LoadLibrary(fileName);
if (Handle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Exception(string.Format("Failed to load library (ErrorCode: {0})",errorCode));
}
//Free
if(Handle != IntPtr.Zero)
FreeLibrary(Handle);
If you want to call functions first you must create delegate that matches this function and then use WinApi GetProcAddress
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
IntPtr funcaddr = GetProcAddress(Handle,functionName);
YourFunctionDelegate function = Marshal.GetDelegateForFunctionPointer(funcaddr,typeof(YourFunctionDelegate )) as YourFunctionDelegate ;
function.Invoke(pass here your parameters);
Create a worker process that communicates via COM or another IPC mechanism. Then when the DLL dies, you can just restart the worker process.
Load the dll, call it, and then unload it till it's gone.
I've adapted the following code from the VB.Net example here.
[DllImport("powrprof.dll")]
static extern bool IsPwrHibernateAllowed();
[DllImport("kernel32.dll")]
static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32.dll")]
static extern bool LoadLibraryA(string hModule);
[DllImport("kernel32.dll")]
static extern bool GetModuleHandleExA(int dwFlags, string ModuleName, ref IntPtr phModule);
static void Main(string[] args)
{
Console.WriteLine("Is Power Hibernate Allowed? " + DoIsPwrHibernateAllowed());
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private static bool DoIsPwrHibernateAllowed()
{
LoadLibraryA("powrprof.dll");
var result = IsPwrHibernateAllowed();
var hMod = IntPtr.Zero;
if (GetModuleHandleExA(0, "powrprof", ref hMod))
{
while (FreeLibrary(hMod))
{ }
}
return result;
}

Categories

Resources