I tried to uset IDataObject to put a some text to clipboard. But the GlobalUnlock fails. What I'm doing wrong?
IDataObject *obj;
HRESULT ret;
assert(S_OK == OleGetClipboard(&obj));
FORMATETC fmtetc = {0};
fmtetc.cfFormat = CF_TEXT;
fmtetc.dwAspect = DVASPECT_CONTENT;
fmtetc.lindex = -1;
fmtetc.tymed = TYMED_HGLOBAL;
STGMEDIUM medium = {0};
medium.tymed = TYMED_HGLOBAL;
char* str = "string";
medium.hGlobal = GlobalAlloc(GMEM_MOVEABLE+GMEM_DDESHARE, strlen(str)+1);
char* pMem = (char*)GlobalLock(medium.hGlobal);
strcpy(pMem,str);
assert(GlobalUnlock(medium.hGlobal) != 0); // !!! ERROR
assert(S_OK == obj->SetData(&fmtetc,&medium,TRUE));
assert(S_OK == OleSetClipboard(obj));
Well, after looking at the documentation this is to be expected:
Return Value
If the memory object is still locked after decrementing the lock count, the return value is a nonzero value. If the memory object is unlocked after decrementing the lock count, the function returns zero and GetLastError returns NO_ERROR.
If the function fails, the return value is zero and GetLastError returns a value other than NO_ERROR.
So your assertion is wrong; it should be:
assert(GlobalUnlock(medium.hGlobal) == 0 && GetLastError() == NO_ERROR);
Related
In the function below I am facing a Dereference error before null check. In the line
SEC_KM_KEKColumn_t *pAdmin1KEKs = pTCGKS->keySet[SEC_KM_Admin1].kc;
There is an error which states directly dereferencing pointer pTCGKS. And also in the line
SEC_ASSERT_MODEL(pDefaultKS != NULL && pTCGKS != NULL);
there is an error which states Dereference before null check (REVERSE_INULL)
check_after_deref: Null-checking pTCGKS suggests that it may be null, but it has already been dereferenced on all paths leading to the check.
Stat_t SEC_COD_SLOW SEC_KM_TCG_Activ(SEC_KM_TCGKeySet_t *pTCGKS, uint32_t rangesSUM, SEC_KM_DefaultKeySet_t *pDefaultKS)
{
Status_t status = STATUS_OK;
uint32_t rangeIndex = 0;
const SEC_KM_KDF_t *pDigestNID = SEC_KM_GetAnybodyDigest();
SEC_KM_KEKColumn_t *pAdmin1KEKs = pTCGKS->keySet[SEC_KM_Admin1].kc;
const SEC_KM_KDF_t *pDigestAID = SEC_KM_TCG_GetSessionCredentials();
SEC_ASSERT_DEBUG(SEC_KM_TCG_GetSessionUserID() == SEC_KM_Admin1);
SEC_ASSERT_MODEL(pDefaultKS != NULL && pTCGKS != NULL);
// Generate Key Chains for all TCG authorities for Original Opal scheme
status = SEC_KM_TCG_Generate(pTCGKS, pDigestNID, pDigestAID);
if (status != STATUS_OK)
{
return status;
}
// Rewrap SDEK from default key storage into Global Range of TCG
status = SEC_KM_RewrapSDEK(&pDefaultKS->SDEKw, &pDefaultKS->keySet.RKEKw, &pDefaultKS->keySet.PKEKw, pDigestNID,
&pTCGKS->DEK[GDEK].SDEK.w, &pAdmin1KEKs[RKEKG].w, &pAdmin1KEKs[PKEK].w, pDigestAID);
if (status != STATUS_OK)
{
return status;
}
status = SEC_KM_TCG_ConvertToSUM(pTCGKS, pDigestNID, rangesSUM);
if (status != STATUS_OK)
{
return status;
}
// After Activation all ranges are unlocked. So unwrap all SDEKs.
for (rangeIndex = 0; rangeIndex < TCG_MAX_RANGE_KEYS; rangeIndex++)
{
status = SEC_KM_TCG_UnwrapUnlockedSDEK(pTCGKS, rangeIndex);
if (status != STATUS_OK)
{
return status;
}
}
return status;
}
It's exactly what it says.
First you dereference pTCGKS, then you check that it isn't null.
Compilers can (and will) optimise out a "late" null check as being effectively redundant for any well-defined program, making your assertion potentially useless.
Move it to before your dereference.
The SEC_ASSERT_MODEL checks for NULL after the line that references it. If pTCGKS is null a runtime error will occur before that check, so it serves no useful purpose.
I assume SEC_ASSERT_MODEL is a precondition check macro - if that is the case you need to perform those checks before using the checked parameters:
SEC_ASSERT_DEBUG(SEC_KM_TCG_GetSessionUserID() == SEC_KM_Admin1);
SEC_ASSERT_MODEL(pDefaultKS != NULL && pTCGKS != NULL);
Status_t status = STATUS_OK;
uint32_t rangeIndex = 0;
const SEC_KM_KDF_t *pDigestNID = SEC_KM_GetAnybodyDigest();
SEC_KM_KEKColumn_t *pAdmin1KEKs = pTCGKS->keySet[SEC_KM_Admin1].kc;
const SEC_KM_KDF_t *pDigestAID = SEC_KM_TCG_GetSessionCredentials();
I have this function which simply encrypts a string (this function works fine, and tested).
DWORD SomeObj::Encrypt(string * To_Enc) {
DWORD text_len = (To_Enc->length());
if (!CryptEncrypt(this->hKey,
NULL, // hHash = no hash
1, // Final
0, // dwFlags
(PBYTE)(*To_Enc).c_str(), //*pbData
&text_len, //*pdwDataLen
128)) { //dwBufLen
return SERVER_ERROR;
}
return SERVER_SUCCESS;
}
And I have this piece of code:
string s= "stringTest";
Encrypt(&s);
which simply call the function passing the pointer of a string.
The program is causing an access violation exception right when it calls the function Encrypt(&s), I guess that it's something about the parameter &s being passed but I can't figure this out. Any idea from your experience ?
This answer will reiterate important points already made in the comments, with example code.
Your current code:
DWORD SomeObj::Encrypt(string * To_Enc) {
DWORD text_len = (To_Enc->length());
if (!CryptEncrypt(this->hKey,
NULL, // hHash = no hash
1, // Final
0, // dwFlags
(PBYTE)(*To_Enc).c_str(), //*pbData
&text_len, //*pdwDataLen
128)) { //dwBufLen
return SERVER_ERROR;
}
return SERVER_SUCCESS;
}
On the line:
(PBYTE)(*To_Enc).c_str(), //*pbData
Note that you are casting away const-ness from the pointer value returned from the c_str() method call.
This should immediately be a red flag; there may be times when casting away const-ness is a valid use case, but it is more the exception than the rule.
Untested, but using a temporary, mutable buffer should solve your problem, such as:
#include <cstddef>
#include <vector>
...
DWORD SomeObj::Encrypt(string * To_Enc) {
std::vector<std::string::value_type> vecBuffer(To_Enc->length() * 3, 0); // use the maximum value that could be output, possibly some multiple of the length of 'To_Enc'
std::size_t nIndex = 0;
for (auto it = To_Enc->cbegin(); it != To_End->cend(); ++it)
{
vecBuffer[nIndex++] = *it;
}
DWORD text_len = (To_Enc->length());
if (!CryptEncrypt(this->hKey,
NULL, // hHash = no hash
1, // Final
0, // dwFlags
reinterpret_cast<PBYTE>(&vecBuffer[0]), //*pbData
&text_len, //*pdwDataLen
vecBuffer.size())) { //dwBufLen
return SERVER_ERROR;
}
To_Enc->assign(&vecBuffer[0], text_len); // assumes 'text_len' is returned with the new length of the buffer
return SERVER_SUCCESS;
}
I'm trying to share an array of structs through shared named memory using the WINAPI. I'm able to create and manage the shared memory but when trying to share an array of structs the size of the array is always 0 upon reading.
Below is test code i have written which should write/read an array of 10 entries, but even this is failing. My goal is however to write/read a dynamic array of structs containing 2 dynamic arrays and the info they already contain at the moment.
I'm aware i shouldn't share pointers between processes as they could point to a random value. Therefor i'm allocating memory for the arrays using new.
This is what i have so far:
Shared in both processes:
#define MEMSIZE 90024
typedef struct {
int id;
int type;
int count;
} Entry;
Process 1:
extern HANDLE hMapObject;
extern void* vMapData;
std::vector<Entry> entries;//collection of entries
BOOL DumpEntries(TCHAR* memName) {//Returns true, writing 10 entries
int size = min(10, entries.size());
Entry* eArray = new Entry[size];
for (int i = 0; i < size; i++) {
eArray[i] = entries.at(i);
}
::hMapObject = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, MEMSIZE, memName);
if (::hMapObject == NULL) {
return FALSE;
}
::vMapData = MapViewOfFile(::hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, MEMSIZE);
if (::vMapData == NULL) {
CloseHandle(::hMapObject);
return FALSE;
}
CopyMemory(::vMapData, eArray, (size * sizeof(Entry)));
UnmapViewOfFile(::vMapData);
//delete[] eArray;
return TRUE;
}
Process 2:
BOOL ReadEntries(TCHAR* memName, Entry* entries) {//Returns true reading 0 entries
HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, memName);
if (hMapFile == NULL) {
return FALSE;
}
Entry* tmpEntries = (Entry*)(MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 10 * sizeof(Entry)));
if (tmpEntries == NULL) {
CloseHandle(hMapFile);
return FALSE;
}
entries = new Entry[10];
for (int i = 0; i < 10; i++) {
entries[i] = tmpEntries[i];
}
UnmapViewOfFile(tmpEntries);
CloseHandle(hMapFile);
return TRUE;
}
Writing the 10 entries seems to be working but when trying to read the memory it returns successfully and the size
of the array is 0, like so:
Entry* entries = NULL;
if (ReadEntries(TEXT("Global\Entries"), entries)) {
int size = _ARRAYSIZE(entries);
out = "Succesfully read: " + to_string(size);// Is always 0
}
So my question is, what am I doing wrong? I'm sharing the same struct between 2 processes, i'm allocating new memory for the entries to be written to and copying the memory with a size of 10 * sizeof(Entry);. When trying to read I also try to read 10 * sizeof(Entry); bytes and cast the data to a Entry*. Is there something I'm missing? All help is welcome.
Based on cursory examination, this code appears to attempt to map structures containing std::strings into shared memory, to be used by another process.
Unfortunately, this adventure is doomed, before it even gets started. Even if you get the array length to pass along correctly, I expect the other process to crash immediately, as soon as it even smells the std::string that the other process attempted to map into shared memory segments.
std::strings are non-trivial classes. A std::string maintains internal pointers to a buffer where the actual string data is kept; with the buffer getting allocated on the heap.
You do understand that sizeof(std::string) doesn't change, whether the string contains five characters, or the entire contents of "War And Peace", right? Stop and think for a moment, how that's possible, in just a few bytes that it takes to store a std::string?
Once you think about it for a moment, it should become crystal clear why mapping one process's std::strings into a shared memory segment, and then attempting to grab them by another process, is not going to work.
The only thing that can be practically mapped to/from shared memory is plain old data; although you could get away with aggregates, in some cases, too.
I'm afraid the problem only lies in the _ARRAYSIZE macro. I could not really find it in MSDN, but I found references for _countof or ARRAYSIZE in other pages. All are defined as sizeof(array)/sizeof(array[0]). The problem is that it only make sense for true arrays defined as Entry entries[10], but not for a pointer to such an array. Technically when you declare:
Entry* entries;
sizeof(entries) is sizeof(Entry *) that is the size of a pointer. It is smaller than the size of the struct so the result of the integer division is... 0!
Anyway, there are other problems in current code. The correct way to exchange a variable size array through shared memory is to use an ancillary structure containing a size and the array itself declared as incomplete:
struct EntryArray {
size_t size;
Entry entries[];
};
You could dump it that way:
BOOL DumpEntries(TCHAR* memName) {//Returns true, writing 10 entries
int size = min(10, entries.size());
EntryArray* eArray = (EntryArray *) malloc(sizeof(EntryArray) + size * sizeof(Entry));
for (int i = 0; i < size; i++) {
eArray->entries[i] = entries.at(i);
}
eArray->size = size;
::hMapObject = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, MEMSIZE, memName);
if (::hMapObject == NULL) {
return FALSE;
}
::vMapData = MapViewOfFile(::hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, MEMSIZE);
if (::vMapData == NULL) {
CloseHandle(::hMapObject);
return FALSE;
}
CopyMemory(::vMapData, eArray, (sizeof(EntryArray) + size * sizeof(Entry)));
UnmapViewOfFile(::vMapData);
free(eArray);
return TRUE;
}
You can note that as the last member of the struct is an incomplete array, it is allocated 0 size, so you must allocate the size of the struct + the size of the array.
You can then read it from memory that way:
size_t ReadEntries(TCHAR* memName, Entry*& entries) {//Returns the number of entries or -1 if error
HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, memName);
if (hMapFile == NULL) {
return -1;
}
EntryArray* eArray = (EntryArray*)(MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 10 * sizeof(Entry)));
if (eArray == NULL) {
CloseHandle(hMapFile);
return -1;
}
entries = new Entry[10]; // or even entries = new Entry[eArray->size];
for (int i = 0; i < 10; i++) { // same: i<eArray->size ...
entries[i] = eArray->entries[i];
}
UnmapViewOfFile(eArray);
CloseHandle(hMapFile);
return eArray.size;
}
But here again you should note some differences. As the number of entries is lost when eArray vanishes, it is passed as the return value from the function. And and you want to modify the pointer passed as second parameter, you must pass it by reference (if you pass it by value, you will only change a local copy and still have NULL in original variable after function returns).
There are still some possible improvement in your code, because the vector entries is global when it could be passed as a parameter to DumpEntries, and hMapObject is also global when it could be returned by the function. And in DumpObject you could avoid a copy by building directly the EntryArray in shared memory:
HANDLE DumpEntries(TCHAR* memName, const std::vector<Entry>& entries) {
//Returns HANDLE to mapped file (or NULL), writing 10 entries
int size = min(10, entries.size());
HANDLE hMapObject = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, MEMSIZE, memName);
if (hMapObject == NULL) {
return NULL;
}
void * vMapData = MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, MEMSIZE);
if (vMapData == NULL) {
CloseHandle(hMapObject);
return NULL;
}
EntryArray* eArray = (EntryArray*) vMapData;
for (int i = 0; i < size; i++) {
eArray->entries[i] = entries.at(i);
}
eArray->size = size;
UnmapViewOfFile(vMapData);
return hMapObject;
}
And last but not least, the backslash \ is a special quoting character in a string litteral, and it must quote itself. So you should write .TEXT("Global\\Entries")
I did it some changes to your code:
PROCESS 1:
BOOL DumpEntries(TCHAR* memName)
{
int size = entries.size() * sizeof(Entry) + sizeof(DWORD);
::hMapObject = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, size, memName);
if (::hMapObject == NULL) {
return FALSE;
}
::vMapData = MapViewOfFile(::hMapObject, FILE_MAP_ALL_ACCESS, 0, 0, size);
if (::vMapData == NULL) {
CloseHandle(::hMapObject);
return FALSE;
}
(*(DWORD*)::vMapData) = entries.size();
Entry* eArray = (Entry*)(((DWORD*)::vMapData) + 1);
for(int i = entries.size() - 1; i >= 0; i--) eArray[i] = entries.at(i);
UnmapViewOfFile(::vMapData);
return TRUE;
}
PROCESS 2:
BOOL ReadEntries(TCHAR* memName, Entry** entries, DWORD &number_of_entries) {
HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, memName);
if (hMapFile == NULL) {
return FALSE;
}
DWORD *num_entries = (DWORD*)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
if (num_entries == NULL) {
CloseHandle(hMapFile);
return FALSE;
}
number_of_entries = *num_entries;
if(number_of_entries == 0)
{
// special case: when no entries was found in buffer
*entries = NULL;
return true;
}
Entry* tmpEntries = (Entry*)(num_entries + 1);
*entries = new Entry[*num_entries];
for (UINT i = 0; i < *num_entries; i++) {
(*entries)[i] = tmpEntries[i];
}
UnmapViewOfFile(num_entries);
CloseHandle(hMapFile);
return TRUE;
}
PROCESS 2 (usage example):
void main()
{
Entry* entries;
DWORD number_of_entries;
if(ReadEntries(TEXT("Global\\Entries", &entries, number_of_entries) && number_of_entries > 0)
{
// do something
}
delete entries;
}
CHANGES:
I am not using a static size (MEMSIZE) when i map memory, i am calculating exactly memory requiered
I put a "header" to memory mapped, a DWORD for send to process 2 number of entries in buffer
your ReadEntries definition is wrong, i fix it changing Entry* to Entry**
NOTES:
you need to close ::hMapObject handle in process 1 before process 2 calls ReadEntries
you need to delete entries memory returned for ReadEntries in process 2, before you use it
this code works only under same windows user, if you want to communicate a services with user process (for example), you need to handle SECURITY_ATTRIBUTES member in CreateFileMapping procedure
I am using the Cassandra C++ driver in my application. I am observing many crashes. After debugging I identified that even when the query output is zero rows , the if (result == NULL) is false and when I iterate through the result, one place or other it is crashing. Below is the code sample. Please suggest me any solution for this.
const char* query = "SELECT variable_id, variable_name FROM aqm_wfvariables WHERE template_id = ?;";
CassError rc = CASS_OK;
CassSession* session = NULL;
if((session=CassandraDbConnect::getInstance()->getSessionForCassandra())==NULL){
return false;
}
CassStatement* statement = cass_statement_new(query, 1);
cass_statement_bind_int32(statement, 0, wf_template_id );
CassFuture* query_future = cass_session_execute(session, statement);
cass_future_wait(query_future);
rc = cass_future_error_code(query_future);
if (rc != CASS_OK) {
logMsg(DEBUG, 7, "cass_session_execute failed for query #%d:%s:%s", 1, __FILE__, query);
cass_statement_free(statement);
return false;
}
cass_statement_free(statement);
const CassResult* result = cass_future_get_result(query_future);
if (result == NULL) {
cass_future_free(query_future);
logMsg(DEBUG, 7, "No values are returned for query #%d:%s:%s", 1, __FILE__, query);
return false;
}
cass_future_free(query_future);
CassIterator* row_iterator = cass_iterator_from_result(result);
while (cass_iterator_next(row_iterator)) {
const CassRow* row = cass_iterator_get_row(row_iterator);
/* Copy data from the row */
You should use
(result.cass_result_row_count>0)
instead of
(result == NULL)
to verify if query returns zero rows. In your code, result is always an instance of CassResult and not a null reference when zero rows are returned.
Currently, I am trying hard to get a safearray of variants to work in my c++ code below. As you can see I call QueueInputReport which has a signature of (SAFEARRAY * psainputreport, UNIT timeoutduration):
CComSafeArray<VARIANT> savt;
//LONG j[5];
LONG length = 4;
//SafeArrayLock(psaValues);
for(LONG i = 0; i <= length; ++i)
{
//j[i] = i;
MessageBox(NULL,L"inputreport assigned to variable",NULL,NULL);
//VariantInit(&pDescriptorData[i]);
//pDescriptorData[i].vt = VT_UI1;
//pDescriptorData[i].bVal = inputreport[i];
//SafeArrayPutElement(psaValues,&i,&pDescriptorData[i]);
// VariantClear(&pDescriptorData[i]);
savt.Add(CComVariant(inputreport[i]));
}
//SafeArrayUnlock(psaValues);
MessageBox(NULL,L"data is successfully assigned to safearray",L"correct data format",NULL);
//FADF_STATIC+FADF_FIXEDSIZE+FADF_HAVEVARTYPE+FADF_VARIANT;
/* _TCHAR szBuffer2[100];
_stprintf_s(szBuffer2, _T("%i"),&psaValues->fFeatures);
MessageBox(NULL,L"safe array type",szBuffer2,NULL);*/
piSoftHidDevice1[devindex]->QueueInputReport(savt,8);
piSoftHidDevice1[devindex]->StartProcessing();
piSoftHidDevice1[devindex]->StopProcessing();
Edit: below is the code for queueinputreport which I needed to pass data to.
STDMETHODIMP CHIDDevice::QueueInputReport( SAFEARRAY* psaInputReport, UINT timeoutDuration )
/*++
Routine Description: Queues additional input reports
Arguments:
IdleTimeout - used to set the value of the log level
Return value:
S_OK
--*/
{
VARIANT * pArrayData = NULL;
UINT cbData = 5;
LONG lLBound = 0;
LONG lUBound = 0;
HRESULT hr = S_OK;
HID_INPUT_REPORT inputReport;
BOOLEAN result = TRUE;
// Initialize Structure
inputReport.timeout = timeoutDuration;
inputReport.cbInputReport = 0;
inputReport.pbInputReport = NULL;
MessageBox(NULL,L"report initialized",L"initial report",NULL);
// Get SAFEARRAY size
IfFailHrGo(SafeArrayGetLBound(psaInputReport, 1, &lLBound));
IfFailHrGo(SafeArrayGetUBound(psaInputReport, 1, &lUBound));
IfFalseHrGo(lUBound > lLBound, E_UNEXPECTED);
cbData = lUBound - lLBound + 1;
//psaInputReport->fFeatures = 0x892;
//psaInputReport->fFeatures = 0x892;
inputReport.pbInputReport = (BYTE*)CoTaskMemAlloc( cbData * sizeof(BYTE) );
_TCHAR szBuffer3[100];
_stprintf_s(szBuffer3, _T("%i"), &psaInputReport->fFeatures);
MessageBox(NULL,L"array content features",szBuffer3,NULL);
// If the memory Allocation fails, then fail and exit
if( inputReport.pbInputReport == NULL )
{
hr = E_UNEXPECTED;
goto Exit;
}
//void HUGEP** cast orginally
IfFailHrGo( SafeArrayAccessData( psaInputReport,
reinterpret_cast<void HUGEP**>(&pArrayData) ) );
// Step through the SAFEARRAY and populating only BYTE input report
// and bail out if the type is not correct
for( LONG i = 0; i <= lUBound; ++i )
{
if (pArrayData[i].vt == VT_UI1)
{
inputReport.pbInputReport[i] = pArrayData[i].bVal;
}
else
{
hr = E_FAIL;
goto Exit;
}
}
SafeArrayUnaccessData(psaInputReport);
inputReport.cbInputReport = cbData;
//MessageBox(NULL,L"report being sent next",L"sent report",NULL);
// Add the report to the input queue (does a shallow copy so no need to free the array data)
result = m_InputReportQueue.insert( inputReport );
if (result == FALSE)
{
MessageBox(NULL,L"failed to queue the input",NULL,NULL);
hr = E_FAIL;
}
return hr;
Exit:
SafeArrayUnaccessData(psaInputReport);
if( FAILED(hr) )
{
CoTaskMemFree(inputReport.pbInputReport);
}
return hr;
}
Edit: The problem is I need the fFeatures to equal 2194 and it is currently its a very high number. What could I be doing wrong?
In vbscript, I have some working code for the queueinputreport:
........(too numerous code to list here but it represents the device I am sending input to (i.e. device #1,#2,#3))
Here's some more information on the fFeatures Iam talking about:
http://msdn.microsoft.com/en-us/library/cc237824.aspx
Dim inputreport(5)
inputreport(0) = CByte(0)
inputreport(1) = CByte(100)
inputreport(2) = CByte(100)
inputreport(3) = CByte(0)
inputreport(4) = Cbyte(0)
pisofthiddevice1(i).QueueInputReport(inputreport, 8)
However, when I try replicating this in C++ above it does not work.