StringToCoTaskMemUni or StringToCoTaskMemAnsi methods can cause hang? - c++-cli

I have the below code in c++/CLI and observing hang while converting the .net string to char * using StringToCoTaskMemAnsi
const char* CDICashInStringStore::CDIGetStringVal( void )
{
unsigned int identifier = (unsigned int)_id;
debug(" cashincdistores--routing call to .Net for CDI String %d", identifier);
NCR::APTRA::INDCDataAccess::IStringValue^ stringValueProvider = (NCR::APTRA::INDCDataAccess::IStringValue^)GetStringProvider()->GetProvider();
String^ strValue = stringValueProvider->GetStringValue(identifier);
debug(" cashincdistores-- going to call StringToCoTaskMemAnsi);
IntPtr iPtr = Marshal::StringToCoTaskMemAnsi(strValue);
debug(" cashincdistores-- StringToCoTaskMemAnsi called);
// use a local (retVal is not needed)
const char * ansiStr = strdup((const char *) iPtr.ToPointer());
Marshal::FreeCoTaskMem(iPtr);
debug(" cashincdistores--got results %d %s",identifier,ansiStr);
// The returned memory will be free() 'ed by the user
return ansiStr;
}
In our logging I can see "cashincdistores-- going to call StringToCoTaskMemAnsi" and suspecting there is a hang after calling the 'StringToCoTaskMemAnsi' method.
Does there is a chance of hang in 'StringToCoTaskMemAnsi' marshalling method. what could cause the hang ?

Why are you using COM in the first place? You don't need any COM in that code.
Disclaimer: You should probably not be returning a const char * someone else will have to free from your function. That's a very easy way to produce memory leaks or multiple free errors.
Ignoring the disclaimer above, you have a couple possibilities:
First way:
#include <msclr/marshal.h>
msclr::interop::marshal_context context;
const char* strValueAsCString = context.marshal_as<const char*>(strValue);
// Probably bad
const char* ansiStr = strdup(strValueAsCString);
The strValueAsCString pointer will remain valid as long as context is in scope.
Another way:
#include <string>
#include <msclr/marshal_cppstd.h>
std::string strValueAsStdString = msclr::interop::marshal_as<std::string>(strValue);
// Probably bad
const char* ansiStr = strdup(strValueAsStdString.c_str());
Here, the std::string manages the lifetime of the string.
See Overview of Marshaling for reference.

Related

Pass LPWSTR to C# [duplicate]

I need to convert my SHA1 (wchar_t*) to a normal String^ in order to use it in a certain function. Any ideas? I tried Google but all the results were the exact opposite of my question. :\
NOTE: I am using C++.NET framework and Windows Forms Applications
Use the constructor; like this:
const wchar_t* const pStr1 = ...;
System::String^ const str1 = gcnew System::String(pStr1);
const char* const pStr2 = ...;
System::String^ const str2 = gcnew System::String(pStr2);
If you're using the standard C++ string classes (std::wstring or std::string), you can get a pointer with the c_str() method. Your code then might be
const std::wstring const std_str1 = ...;
System::String^ const str1 = gcnew System::String(std_str1.c_str());
See System.String and extensive discussion here.
If on doing Dan's solution you get an error cannot convert parameter 1 from 'std::string' to 'const wchar_t *', then you're asking the wrong question. Instead of asking how to convert wchar_t* to String^, you should be asking how to convert std::string to String^.
Use the built-in c_str function to get a plain char* out of the std::string, and pass that to the constructor.
std::string unmanaged = ...;
String^ managed = gcnew String(unmanaged.c_str());
You could also try:
#include <msclr\marshal_cppstd.h>
...
String^ managedString = msclr::interop::marshal_as<String^>(/* std::string or wchar_t * or const wchar_t * */);
You can refer to Overview of Marshaling in C++ for all the supported types you could use

C Blocks indirection and misalignment

The following code throws an EXC_BAD_ACCESS error (specifically a general protection fault error) and I would like to know why you cannot misalign a block pointer and execute it.
#include <stdio.h>
int main(int argc, const char * argv[])
{
void (^blocky)() = ^{
printf("Hello!\n");
printf("Hello Again!\n");
};
blocky = *(&blocky+1);
blocky = *(&blocky-1);
blocky();
return 0;
}
But the following works:
#include <stdio.h>
int main(int argc, const char * argv[])
{
void (^blocky)() = ^{
printf("Hello!\n");
printf("Hello Again!\n");
};
blocky = *(&blocky+1-1);
blocky();
return 0;
}
Edit (answer to misaligning code blocks):
If you treat a block like a structure, you can find that the value that points to the executable code in memory is offset 16 bytes from the start of the block and is 8 bytes long.
You are able to change this value effectively pointing execution to another place in memory. Generally, this will crash.
Assuming you know the specific address in memory for another piece of executable code, you may direct it there.
Why this is useful:
It isn't. Never do this. Really. Never.
The pointer manipulation in the first example is wrong. Try this:
#include <stdio.h>
typedef void (^blocky_t)();
int main(int argc, const char * argv[])
{
blocky_t blocky = ^{
printf("Hello!\n");
printf("Hello Again!\n");
};
printf("blocky=%p\n", blocky);
blocky = (blocky_t)((char *)blocky + 1);
printf("blocky=%p\n", blocky);
blocky = (blocky_t)((char *)blocky - 1);
printf("blocky=%p\n", blocky);
blocky();
return 0;
}
$ clang -o blocky blocky.c
$ ./blocky
blocky=0x10574d040
blocky=0x10574d041
blocky=0x10574d040
Hello!
Hello Again!
When I ran your code, I got:
blocky=0x10e0ba040
blocky=0x7fff51b46c10
blocky=0x1300000000
Where:
The first address is within the __TEXT segment of the program.
The second address is near the stack.
The third is who-knows-where.
Your question really has nothing to do with blocks. You're just manipulating pointers to local variables in a way that doesn't make sense.
First, you never use the block pointer that you assign to blocky. You take the address of the local variable blocky on the stack, and then add one word to it, and dereference it. Depending on the architecture, the stack probably grows down, which means this is before all the variables on the stack frame, and is probably the return address of the current stack frame. Or it may be something else. You then assign this value to blocky.
Then, you take the address of the local variable blocky on the stack again, and then subtract one word from it, and dereference it. Again, assuming the stack grows down, this might be past the end of the current stack frame, which would be garbage. You then assign this value to blocky. You then try to run this as a pointer to a block. Of course this doesn't work.
In the second piece of code, you take the address of the local variable blocky on the stack again, and then add and subtract one word from it (which of course is the pointer to the local variable blocky again), and dereference it (which is the value of blocky), and assign it to blocky. This operation does nothing.

Is there a way to wrap an ObjectiveC block into function pointer?

I have to provide a C-style callback for a specific C library in an iOS app. The callback has no void *userData or something similar. So I am not able to loop in a context. I'd like to avoid introducing a global context to solve this. An ideal solution would be an Objective-C block.
My question: Is there a way to 'cast' a block into a function pointer or to wrap/cloak it somehow?
Technically, you could get access to a function pointer for the block. But it's totally unsafe to do so, so I certainly don't recommend it. To see how, consider the following example:
#import <Foundation/Foundation.h>
struct Block_layout {
void *isa;
int flags;
int reserved;
void (*invoke)(void *, ...);
struct Block_descriptor *descriptor;
};
int main(int argc, char *argv[]) {
#autoreleasepool {
// Block that doesn't take or return anything
void(^block)() = ^{
NSLog(#"Howdy %i", argc);
};
// Cast to a struct with the same memory layout
struct Block_layout *blockStr = (struct Block_layout *)(__bridge void *)block;
// Now do same as `block()':
blockStr->invoke(blockStr);
// Block that takes an int and returns an int
int(^returnBlock)(int) = ^int(int a){
return a;
};
// Cast to a struct with the same memory layout
struct Block_layout *blockStr2 = (struct Block_layout *)(__bridge void *)returnBlock;
// Now do same as `returnBlock(argc)':
int ret = ((int(*)(void*, int a, ...))(blockStr2->invoke))(blockStr2, argc);
NSLog(#"ret = %i", ret);
}
}
Running that yields:
Howdy 1
ret = 1
Which is what we'd expect from purely executing those blocks directly with block(). So, you could use invoke as your function pointer.
But as I say, this is totally unsafe. Don't actually use this!
If you want to see a write-up of a way to do what you're asking, then check this out:
http://www.mikeash.com/pyblog/friday-qa-2010-02-12-trampolining-blocks-with-mutable-code.html
It's just a great write-up of what you would need to do to get this to work. Sadly, it's never going to work on iOS though (since you need to mark a page as executable which you're not allowed to do within your app's sandbox). But nevertheless, a great article.
If your block needs context information, and the callback does not offer any context, I'm afraid the answer is a clear no. Blocks have to store context information somewhere, so you will never be able to cast such a block into a no-arguments function pointer.
A carefully designed global variable approach is probably the best solution in this case.
MABlockClosure can do exactly this. But it may be overkill for whatever you need.
I know this has been solved but, for interested parties, I have another solution.
Remap the entire function to a new address space. The new resulting address can be used as a key to the required data.
#import <mach/mach_init.h>
#import <mach/vm_map.h>
void *remap_address(void* address, int page_count)
{
vm_address_t source_address = (vm_address_t) address;
vm_address_t source_page = source_address & ~PAGE_MASK;
vm_address_t destination_page = 0;
vm_prot_t cur_prot;
vm_prot_t max_prot;
kern_return_t status = vm_remap(mach_task_self(),
&destination_page,
PAGE_SIZE*(page_count ? page_count : 4),
0,
VM_FLAGS_ANYWHERE,
mach_task_self(),
source_page,
FALSE,
&cur_prot,
&max_prot,
VM_INHERIT_NONE);
if (status != KERN_SUCCESS)
{
return NULL;
}
vm_address_t destination_address = destination_page | (source_address & PAGE_MASK);
return (void*) destination_address;
}
Remember to handle pages that aren't required anymore and note that it takes a lot more memory per invocation than MABlockClosure.
(Tested on iOS)

SSH Keyboard Interactive authentication

I currently try to extend an libssh2 Wrapper in Objective-C.
I'm trying to implement the libssh2_userauth_keyboard_interactive method. My problem is the response callback.
I found this implementation on the net that bypasses the "real" interactivity and uses the actual password to make the authentication possible:
int error = libssh2_userauth_keyboard_interactive(session, [username UTF8String], &kbdCallback);
static void kbdCallback (const char *name, int name_len, const char *instruction, int instruction_len, int num_prompts, const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts, LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses, void **abstract)
{
responses[0].text = (char *)[password UTF8String]; // resp. (char *)[#"test" UTF8String]
responses[0].length = strlen([password UTF8String]); // resp. (char *)[#"test" UTF8String]
}
One of my problems is to access the instance variable password within the static void call and my other problem is that I get SIGABRT when I try to call the method (I used a fixed string to test if that works).
Is there any possibility to get that working ?!
Julian
kbdCallback is not actually a method, it's a function - you can tell a couple of ways - there's no - or + in front of it, no parentheses around the return type, and also methods cannot be static. So, due to it being a function and not a method, there is no object associated with it, and no self pointer; thus you cannot get to any instance variables directly. There's a couple of ways to solve this I suppose; you could have a static instance of your object that the function could get the password from, or if there's some way to pass a context pointer to be used in the callback you might be able to pass an object in that way.
Regarding your SIGABRT, can you say which line exactly that happens on, and what the values of the arguments that you're using are? It's not clear from your question.
http://comments.gmane.org/gmane.network.ssh.libssh2.devel/4163
Cause: malloc-in-EXE-free-in-DLL under Win32.
Fix: Use custom free/malloc/realloc functions. Add below
static void *my_alloc(size_t count, void **abstract) { return malloc(count);}
static void my_free(void *ptr, void **abstract) { free(ptr);}
static void *my_realloc(void *ptr, size_t count, void **abstract){ return realloc(ptr, count);}
And replace
libssh2_session_init();
with
libssh2_session_init_ex(my_alloc, my_free, my_realloc, NULL);

How to convert System::IntPtr to char*

can any body tell How to convert System::IntPtr to char* in managed c++
this is my main function
int main(void)
{
String* strMessage = "Hello world";
CManagedClass* pCManagedClass = new CManagedClass();//working
pCManagedClass->ShowMessage(strMessage);//working
****above said error here***
char* szMessage = (char*)Marshal::StringToHGlobalAnsi(strMessage);
CUnmanagedClass cUnmanagedClass; cUnmanagedClass.ShowMessageBox(szMessage);
Marshal::FreeHGlobal((int)szMessage);
return 0;
}
thanks in advance
I'm not a huge C++/CLI programmer, but the following should work just fine.
IntPtr p = GetTheIntPtr();
char* pChar = reinterpret_cast<char*>(p.ToPointer());
The IntPtr class has a method called ToPointer which returns the address as a void* type. That will be convertible to char* in C++/CLI.
EDIT
Verified this works on VS2008 and VS2015
Instead of
char* szMessage = (char*)Marshal::StringToHGlobalAnsi(strMessage).ToPointer();
Marshal::FreeHGlobal((int)szMessage);
Use
marshal_context conversions.
const char* szMessage = conversions.marshal_as<const char*>(strMessage);
It cleans itself up, the magic of C++ RAII.
Attention!
I want to add something to JaredPar answer.I don't know where your IntPtr is coming from but you should also use pin_ptr in order to prevent the garbage collector from messing up your memory. I did lot of CLR/Native inter op in the past and using pin_ptr is one of those things that I learnt to do in the hard way.
read the following:
click me