I call a DLL in ASP.NET a DLL that is written in C++.
When running it into IIS 7, The pool (w3wp.exe) crash and the "just in time debugging window" open.
I do many tracing and I found that crash happen when calling any function (in the unmanaged DLLs) that have a "out string" parameter (or return a string value).
I saw on the web than many people have this problem with their DLL (C, Delphi, VB6). But no answer. so I call experts!
How can I call these functions so IIS 7 process it without error ?
cas sakal
You should use StringBuilder for interop string output parameters:
[MarshalAs(UnmanagedType.LPStr)] StringBuilder myString
It may not be possible. COM provides an interface specification, but not a guarantee that the caller be able to use the interface correctly. Unless the COM object exposes methods which are automatically marshalable by the COM subsystem (eg: automation compatible), you may not be able to use them. It's easily possible to write a C++ COM object which cannot be directly accessed out-of-process, or by any language other than C++.
You may be able to write some custom marshaling code to make it work, but I wouldn't assume it will work directly. If the types are simple/direct enough, there may be some built-in marshal attributes to make it work; I don't have a lot of knowledge in this area, though, so hopefully other people can help out.
Related
I'm writing an add-in that runs in-process. I'm reliably able to discover the memory address of a DLL that is already loaded in that process. The memory at the offset clearly shows an "MZ" DOS header and a "PE" header. Later, there appears to be the names of exported functions etc. This walks and talks like a loaded DLL.
So, now, I'd like to discover more about what the DLL is, and more interestingly, what I might be able to do with it.
I've used PE utilities in the past, but they've always worked with file-based DLLs. How can I list the exported functions of an in-memory DLL, other than by inspecting the process in a hex editor? Is there any way to discover the file-based DLL that is currently loaded? (I'm not overly familiar with the linking that I think takes place when the dll is loaded.)
If I have the names of the exported functions, is it just a matter of trying to call those functions, and guessing their arguments and return values? Or is there some more robust reverse engineering that could be performed?
Given the starting address of the DLL, and a function name, how would I go about making a call in C#?
There are actually many questions here (and some are pretty vast). I'll try providing answers to some.
To get the handle of a module (.dll) loaded in the current process use
[MSDN]: GetModuleHandleEx function, whether its name or address is known (GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS flag)
To get the file name containing the code of a loaded .dll use [MSDN]: GetModuleFileName function. At this point you'll be able to use PE utilities that you mentioned (Dependency Walker or [MSDN]: Sysinternals Suite can be very useful)
Apparently, getting the functions signatures from a .dll is not a trivial task (sometimes it's quite impossible). Here are 3 URLs, but Google would yield tons of results on this topic:
[MSDN]: how can I get metadata (signature with parameters and return type) of C++ dll
[SO]: Is there any native DLL export functions viewer?
[SO]: Get signatures of exported functions in a DLL
But a .dll comes with one or more header file(s) that contain(s) (among other things) the functions/classes declarations. Lacking the header(s) would mean that either:
The .dll symbols are for internal purposes only (and not to be called "manually")
They are private (e.g. protected by a license), and in that case reverse engineering them wouldn't be very ethical
Anyway, considering that one way or another you get the functions names and signatures, you can load the functions via [MSDN]: GetProcAddress function, and then call them.
Doing everything from .NET (C#) (again, function names and signatures are required), only adds an extra level of complexity because C# code runs in managed environment, while C/C++ runs in native environment, and when data is exchanged between the 2 environments it needs to be marshalled/unmarshalled ([MSDN]: Overview of Marshaling in C++).
Below are 3 URLs, but again, Internet is full of information:
[MSDN]: Calling Native Functions from Managed Code
[SO]: Is it possible to call a C function from C#.Net
[SO]: Calling C DLL from C#
I'm trying to configure access, launch permissions along with set run as to one of our custom DCOM application.
I have already gone through these links
dcomcnfg functionality programmatically
and http://www.myitforum.com/articles/11/view.asp?id=9323 (downloaded c++ DCOMPerm library)
I tried the code from the first link above as is written by "longofest" but the following line of code
var value = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Ole", "DefaultAccessPermission", null);
always gives me back a null value,however when I looked into the registry entries on my machine the "DefaultAccessPermission" entry for Ole registry key does have a binary value there then why I always receive a null back, no idea.
Secondly I tried the c++ library downloaded from the second link above and tried to do a COM call to one of the methods with DLLImport attribution (for automating the launch permissions for the DCOM object) but some marshalling issue is not letting me pass in the C# types corresponding to C++ types and spitting out an exception that says PInvoke cannot return variants.
I couldn't find anything concrete after googling for several hours, any help on this account will be more than appreciated.
Never worked with C++, got very poor knowledge of this language.
Update:The null value issue is solved but I don't know how to set access permissions and set run as. I have seen in c++ code that for setting access permission the code needs a domain and username but what is the c# equivalent of that, no idea....
I used the tblimp.exe tool from Microsoft and created an interop .dll assembly out of DComPerm.dll (c++ assembly) to reference in C# code and by means of Run Time Callable Wrapper I'm calling various methods on COM objects to write my C# program, so no need of DLLImport or MarshalAs attribution since RCW will take care of all the marshalling and unmarshalling issues.
So I'm writing a wrapper in C# for a C dll. The problem is several of the functions use complex datatypes e.g.:
ComplexType* CreateComplexType(int a, int b);
Is there a way I can declare a valid C# type such that I can use dllimport?
If I were doing a Windows-only solution I'd probably use C++/CLI as a go-between the native complex type and a managed complex type.
I do have access to the source code of the C dll, so would it be possible to instead use an opaque type (e.g. handles)?
Such a function is difficult to call reliably from a C program, it doesn't get better when you pinvoke it. The issue is memory management, that struct needs to be destroyed again. Which requires the calling program to use the exact same memory allocator as the DLL. This rarely turns out well in a C program but you might be lucky that you have the source code for the DLL so you can recompile it and ensure that everybody is using the same shared CRT version.
There is no such luck from C# of course, the pinvoke marshaller will call CoTaskMemFree() to release the struct. Few real C programs use CoTaskMemAlloc() to allocate the struct so that's a silent failure on XP, an AccessViolationException on Vista and higher. Modern Windows versions have a much stricter heap manager that doesn't ignore invalid pointers.
You can declare the return value as IntPtr, that stops the pinvoke marshaller from trying to destroy it. And then manually marshal with Marshal.PtrToStructure(). This doesn't otherwise stop the memory leak, your program will eventually crash with OOM. Usually anyway.
Mono has a good documentation page on using P/Invoke in Windows vs. Linux. Specifically, see the section on marshaling, that discusses simple vs. complex types. If you want to get creative, you could serialize your type to some convenient string-based format like JSON or XML and use that as your marshaling mechanism.
In my own program I'm trying to use this code here to add tooltip balloon windows to my application: http://www.codeproject.com/Articles/4991/Balloon-Tips-Galore (Source code available here)
I tried compiling the demo program and it works fine on 32-bit Windows 7, but when I try to use it on 64-bit Windows 7 the program crashes. If I try to debug the crash in VS2010 I get this message:
The debugger is in some area where the source code isn't available and it says Call stack location: ntdll.dll!0000000076fe40f2()
How can I fix this so it won't crash on 64-bit?
I can't make the C# demo crash on Windows Server 2003 x64 (which is the only 64-bit environment I have handy at the moment), but the code is faulty so it makes sense that you're seeing unexpected behavior.
Edit: Reproduced the crash in Windows Server 2008 R2 x64 using the original code, and verified the efficacy of the fix.
As Christian.K points out, the problem has been noted before. When calling the Marshal.StructureToPtr method, you should pass true for the third fDeleteOld parameter only when the specified memory block does not contain valid data. This is called out pretty explicitly in the documentation, so I'm not sure how the original writer got it wrong.
In this case, since the data was just allocated the line before by calling Marshal.AllocHGlobal, it does not contain valid data and should not be deleted/freed. The change is simple: change the third parameter true to false. Unfortunately, because the interop code is scattered across three different classes in the sample project, you'll have to make the change multiple places. The pattern you're looking for is this:
IntPtr ptrStruct = Marshal.AllocHGlobal(Marshal.SizeOf(ti));
Marshal.StructureToPtr(ti, ptrStruct, false /* <-- change this from true to false */);
Just as a general observation: the code tries to handle a lot of the interop stuff manually (by using methods of the Marshal class) rather than just letting the CLR handle it automatically. I much prefer the latter method. Even though I fully understand how to do all of the interop manually, letting the system manage it for me keeps down the number of mistakes I make and resulting heap corruption.
RhysW says he's never encountered heap corruption before, but it becomes very common when you start doing interop between .NET code and the Win32 API. The .NET Framework is no longer protecting you.
For an example of what I mean, notice that the FMSBalloonTip.SetToolTip method uses the Marshal.StringToHGlobalAuto method to marshal the string containing the tooltip's title as a pointer. While that certainly works (and the author was thankfully careful to free the pointer after they're finished), it would be much easier and less error-prone to declare an overload of the SendMessage function that accepts a string object as the fourth parameter. That way, the framework will handle all of the necessary interop stuff for you transparently.
The real question, of course, is why you need this code at all. It's way easier to just use the built-in ToolTip class, which has been available since the beginning. I'm not sure if you just didn't mention some feature you need that ToolTip doesn't provide or you just don't know about it, but I strongly recommend reconsidering your design so that you can make use of the built-in class and let the Microsoft programmers handle all of the interop stuff.
If it's the balloon part you're looking for, make sure to set the IsBalloon property of the ToolTip class. That wasn't introduced until .NET 2.0, but that's the same version the sample project is targeting.
Is there such a thing as an x86 assembler that I can call through C#? I want to be able to pass x86 instructions as a string and get a byte array back. If one doesn't exist, how can I make my own?
To be clear - I don't want to call assembly code from C# - I just want to be able to assemble code from instructions and get the machine code in a byte array.
I'll be injecting this code (which will be generated on the fly) to inject into another process altogether.
As part of some early prototyping I did on a personal project, I wrote quite a bit of code to do something like this. It doesn't take strings -- x86 opcodes are methods on an X86Writer class. Its not documented at all, and has nowhere near complete coverage, but if it would be of interest, I would be willing to open-source it under the New BSD license.
UPDATE:
Ok, I've created that project -- Managed.X86
See this project:
https://github.com/ZenLulz/MemorySharp
This project wraps the FASM assembler, which is written in assembly and as a compiled as Microsoft coff object, wrapped by a C++ project, and then again wrapped in C#. This can do exactly what you want: given a string of x86/x64 assembly, this will produce the bytes needed.
If you require the opposite, there is a port of the Udis86 disassembler, fully ported to C#, here:
https://github.com/spazzarama/SharpDisasm
This will convert an array of bytes into the instruction strings for x86/x64
Take a look at Phoenix from Microsoft Research.
Cosmos also has some interesting support for generating x86 code:
http://www.gocosmos.org/blog/20080428.en.aspx
Not directly from C# you can't. However, you could potentially write your own wrapper class that uses an external assembler to compile code. So, you would potentially write the assembly out to a file, use the .NET Framework to spin up a new process that executes the assembler program, and then use System.IO to open up the generated file by the assembler to pull out the byte stream.
However, even if you do all that, I would be highly surprised if you don't then run into security issues. Injecting executable code into a completely different process is becoming less and less possible with each new OS. With Vista, I believe you would definitely get denied. And even in XP, I think you would get an access denied exception when trying to write into memory of another process.
Of course, that raises the question of why you are needing to do this. Surely there's got to be a better way :).
Take a look at this: CodeProject: Using unmanaged code and assembly in C#.
I think you would be best off writing a native Win32 dll. You can then write a function in assembler that is exported from the dll. You can then use C# to dynamically link to the dll.
This is not quite the same as passing in a string and returning a byte array. To do this you would need an x86 assembler component, or a wrapper around masm.exe.
i don't know if this is how it works but you could just shellexecute an external compiler then loading the object generated in your byte array.