hi guys i want read a memory mapped file created by C++ program , i use the MSDN example for create in C++ the memory mapped file , i want read the string in my metatrader 4 i write this code
#property copyright "Copyright © 2005, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"
#property indicator_separate_window
#property indicator_minimum 0
#property indicator_buffers 1
#property indicator_color1 Blue
#define FILE_MAP_READ 4
#define BUF_SIZE 256
extern string szName = "MyFileMappingObject";
//extern string szName = "Global\\dllmemfilemap";
int handle = 0;
string Data;
#import "kernel32.dll"
int OpenFileMappingA(int dwDesiredAccess, bool bInheritHandle, string lpName);
string MapViewOfFile(int hFileMappingObject, int dwDesiredAccess, int dwFileOffsetHigh, int dwFileOffsetLow, int dwNumberOfBytestoMap);
int CloseHandle( int handle);
int UnmapViewOfFile(string lpBaseAddress);
#import
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int start()
{
handle = OpenFileMappingA(FILE_MAP_READ, FALSE, szName);
if(handle == 0)
{
Alert("Could not open file mapping object", GetLastError());
}
else
{
Data = MapViewOfFile(handle, FILE_MAP_READ, 0, 0, BUF_SIZE);
Alert(Data);
UnmapViewOfFile(Data);
CloseHandle(handle);
}
return (0);
}
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
return(0);
}
but not open the OpenFileMappingA, return always 0 , anyone have some idea ? thankz at all
You need to call CreateFileMapping before trying to OpenFileMapping.
See example here :
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#define BUF_SIZE 256
TCHAR szName[]=TEXT("Global\\MyFileMappingObject");
TCHAR szMsg[]=TEXT("Message from first process.");
int _tmain()
{
HANDLE hMapFile;
LPCTSTR pBuf;
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
BUF_SIZE, // maximum object size (low-order DWORD)
szName); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not create file mapping object (%d).\n"),
GetLastError());
return 1;
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL)
{
_tprintf(TEXT("Could not map view of file (%d).\n"),
GetLastError());
CloseHandle(hMapFile);
return 1;
}
CopyMemory((PVOID)pBuf, szMsg, (_tcslen(szMsg) * sizeof(TCHAR)));
_getch();
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
return 0;
}
strings are unicode in MQL, or similarly 2-bytes wchat_t in C++.
Here is a sample :
#include <cstdlib>
#include <cstring>
#include <string>
char* pBufMQL;
std::wstring ss = L"Sample string";
CopyMemory((PVOID)pBufMQL, ss.c_str(), ss.size() * sizeof(wchar_t));
in MQL:
handle = OpenFileMappingW( FILE_MAP_ALL_ACCESS, FALSE, szName);
if(handle == 0)
{
Alert("Could not open file mapping object", GetLastError());
}
string Data = MapViewOfFile(handle, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE);
Print("Done, size: ", StringLen(Data), "-", Data);
p.s. 1: I'm currently struggling with writing from MQL to the buffer and string in MQL are a copy of pBuf(from C++), converted to string.
And I need to modify buffer from MQL.
p.s. 2: p.s. 1 solved, Here is a working example : https://www.mql5.com/en/articles/364#3
Related
I want to be able to get all the issuer data that you can get from Windows Explorer like here:
I've been able to get CN from https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certgetnamestringw, but I don't know what it is about that call that targets the CN (if I did, I might be able to figure how to get everything else). I've tried Googling things like "api wintrust issuer CommonName Organization" and "wincrypt organization commonname" but it's like the API washes its hands of all the other issuer data.
You only need to use CertNameToStr and set the &(pCertContext->pCertInfo->Issuer) parameter:
CertNameToStr(
pCertContext->dwCertEncodingType,
&(pCertContext->pCertInfo->Issuer),
CERT_X500_NAME_STR,
pszString,
cbSize);
I modified the official sample for your reference:
#pragma comment(lib, "crypt32.lib")
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <Wincrypt.h>
#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
#define MY_STRING_TYPE (CERT_OID_NAME_STR)
void MyHandleError(LPTSTR);
void main(void)
{
HCERTSTORE hCertStore;
PCCERT_CONTEXT pCertContext;
if (!(hCertStore = CertOpenStore(
CERT_STORE_PROV_SYSTEM,
MY_ENCODING_TYPE,
NULL,
CERT_SYSTEM_STORE_CURRENT_USER,
L"MY")))
{
MyHandleError(TEXT("The MY system store did not open."));
}
pCertContext = NULL;
while (pCertContext = CertEnumCertificatesInStore(
hCertStore,
pCertContext))
{
LPTSTR pszString;
LPTSTR pszName;
DWORD cbSize;
CERT_BLOB blobEncodedName;
if (!(cbSize = CertGetNameString(
pCertContext,
CERT_NAME_SIMPLE_DISPLAY_TYPE,
0,
NULL,
NULL,
0)))
{
MyHandleError(TEXT("CertGetName 1 failed."));
}
if (!(pszName = (LPTSTR)malloc(cbSize * sizeof(TCHAR))))
{
MyHandleError(TEXT("Memory allocation failed."));
}
if (CertGetNameString(
pCertContext,
CERT_NAME_SIMPLE_DISPLAY_TYPE,
0,
NULL,
pszName,
cbSize))
{
_tprintf(TEXT("\nSubject -> %s.\n"), pszName);
free(pszName);
}
else
{
MyHandleError(TEXT("CertGetName failed."));
}
if (!(cbSize = CertGetNameString(
pCertContext,
CERT_NAME_SIMPLE_DISPLAY_TYPE,
CERT_NAME_ISSUER_FLAG,
NULL,
NULL,
0)))
{
MyHandleError(TEXT("CertGetName 1 failed."));
}
if (!(pszName = (LPTSTR)malloc(cbSize * sizeof(TCHAR))))
{
MyHandleError(TEXT("Memory allocation failed."));
}
if (CertGetNameString(
pCertContext,
CERT_NAME_SIMPLE_DISPLAY_TYPE,
CERT_NAME_ISSUER_FLAG,
NULL,
pszName,
cbSize))
{
_tprintf(TEXT("Issuer -> %s.\n"), pszName);
free(pszName);
}
else
{
MyHandleError(TEXT("CertGetName failed."));
}
cbSize = CertNameToStr(
pCertContext->dwCertEncodingType,
&(pCertContext->pCertInfo->Subject),
MY_STRING_TYPE,
NULL,
0);
if (1 == cbSize)
{
MyHandleError(TEXT("Subject name is an empty string."));
}
if (!(pszString = (LPTSTR)malloc(cbSize * sizeof(TCHAR))))
{
MyHandleError(TEXT("Memory allocation failed."));
}
cbSize = CertNameToStr(
pCertContext->dwCertEncodingType,
&(pCertContext->pCertInfo->Issuer),
CERT_X500_NAME_STR,
pszString,
cbSize);
if (1 == cbSize)
{
MyHandleError(TEXT("Issuer name is an empty string."));
}
else
{
printf("Issuer String = %ls\n", pszString); //what you want
}
if (!(CertStrToName(
MY_ENCODING_TYPE,
pszString,
MY_STRING_TYPE,
NULL,
NULL, // NULL to get the number of bytes
// needed for the buffer.
&cbSize, // Pointer to a DWORD to hold the
// number of bytes needed for the
// buffer
NULL))) // Optional address of a pointer to
// old the location for an error in the
// input string.
{
MyHandleError(
TEXT("Could not get the length of the BLOB."));
}
if (!(blobEncodedName.pbData = (LPBYTE)malloc(cbSize)))
{
MyHandleError(
TEXT("Memory Allocation for the BLOB failed."));
}
blobEncodedName.cbData = cbSize;
if (CertStrToName(
MY_ENCODING_TYPE,
pszString,
MY_STRING_TYPE,
NULL,
blobEncodedName.pbData,
&blobEncodedName.cbData,
NULL))
{
_tprintf(TEXT("CertStrToName created the BLOB.\n"));
}
else
{
MyHandleError(TEXT("Could not create the BLOB."));
}
free(blobEncodedName.pbData);
free(pszString);
}
_tprintf(
TEXT("\nThere are no more certificates in the store. \n"));
if (CertCloseStore(
hCertStore,
CERT_CLOSE_STORE_CHECK_FLAG))
{
_tprintf(TEXT("The store is closed. ")
TEXT("All certificates are released.\n"));
}
else
{
_tprintf(TEXT("The store was closed, ")
TEXT("but certificates still in use.\n"));
}
_tprintf(TEXT("This demonstration program ran to completion ")
TEXT("without error.\n"));
}
void MyHandleError(LPTSTR psz)
{
_ftprintf(stderr,
TEXT("An error occurred in running the program. \n"));
_ftprintf(stderr, TEXT("%s\n"), psz);
_ftprintf(stderr, TEXT("Error number %x.\n"), GetLastError());
_ftprintf(stderr, TEXT("Program terminating. \n"));
exit(1);
}
I try hook file DLL into console app. This code
#include "pch.h"
#include <vector>
#include <string>
#include <windows.h>
#include <Tlhelp32.h>
using std::vector;
using std::string;
int main(void)
{
while (true)
{
vector<string>processNames;
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
HANDLE hTool32 = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
BOOL bProcess = Process32First(hTool32, &pe32);
if (bProcess == TRUE)
{
while ((Process32Next(hTool32, &pe32)) == TRUE)
{
processNames.push_back(pe32.szExeFile);
if (strcmp(pe32.szExeFile, "ConsoleApplication4.exe") == 0)
{
char* DirPath = new char[MAX_PATH];
char* FullPath = new char[MAX_PATH];
GetCurrentDirectory(MAX_PATH, DirPath);
sprintf_s(FullPath, MAX_PATH, "%s\\..\\ConsoleApplication1\\ConsoleApplication1.dll", DirPath);
FILE *pFile;
if (fopen_s(&pFile, FullPath, "r") || !pFile)
{
OutputDebugString("[Hook] File name or file does not exist");
OutputDebugString(FullPath);
return -1;
}
fclose(pFile);
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID);
if (!hProcess)
{
OutputDebugString("[Hook] Open process fail");
return -1;
}
//attach
LPVOID LoadLibraryAddr = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
if (!LoadLibraryAddr)
{
OutputDebugString("[Hook] Load LoadLibraryA fail");
return -1;
}
LPVOID LLParam = (LPVOID)VirtualAllocEx(hProcess, NULL, strlen(FullPath), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (!WriteProcessMemory(hProcess, LLParam, FullPath, strlen(FullPath), NULL))
{
OutputDebugString("[Hook] Write process fail");
return -1;
}
HANDLE hHandle = CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibraryAddr, LLParam, NULL, NULL);
if (!hHandle)
{
OutputDebugString("[Hook] Hooked fail");
return -1;
}
system("pause");
//detach
LoadLibraryAddr = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "FreeLibrary");
if (!LoadLibraryAddr)
{
OutputDebugString("[Hook] Load FreeLibrary fail");
return -1;
}
hHandle = CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibraryAddr, LLParam, NULL, NULL);
if (!hHandle)
{
OutputDebugString("[Hook] detach fail");
return -1;
}
CloseHandle(hProcess);
delete[] DirPath;
delete[] FullPath;
system("pause");
return 0;
}
}
}
CloseHandle(hTool32);
}
return 0;
}
I have some question for this:
- Why this code can not detach file dll ?
- Why I change LoadLibraryA -> LoadLibrary : load LoadLibrary fail ?
- Why I change LoadLibraryA -> LoadLibraryW : file dll no attach ?
- Code in Mutibyte run is good, but convert to Unicode, file dll no attach ?
Thanks,
The reason this works in multibyte but won't compile with unicode character set is because you're passing a regular c string which is a regular char array. When you set your build type to use multibyte LoadLibrary() resolves to the ansi version which is LoadLibraryA(). If you want to use Unicode in your project properties it will resolve to LoadLibraryW() and you will need to pass a unicode char array, typically wchar_t[].
Even while compiling in unicode mode, you can still call LoadLibraryA() and pass a c string but you must specifically call the A (ansi) version of the function rather than rely on the #ifdef preprocessor statements which resolve them for you.
I want to get the Device ID of a USB stick by using the Setup API, but first I am trying to understand some of the functions I have to use. The SetupDiGetDeviceRegistryProperty documentation says I can send NULL to the buffer and buffer size to get the required size, but I am getting the 122 error code, which means:
The data area passed to a system call is too small
Can anyone tell me what am I doing wrong?
Here is my code so far:
#include <Windows.h>
#include <wchar.h>
#include <SetupAPI.h>
#pragma comment(lib, "Setupapi.lib")
int wmain(int argc, wchar_t *arv[])
{
// SetupDiGetClassDevs
HDEVINFO hDeviceInfo;
DWORD filterDevInfo = DIGCF_ALLCLASSES;
hDeviceInfo = SetupDiGetClassDevsW(NULL, NULL, NULL, filterDevInfo);
if (hDeviceInfo != INVALID_HANDLE_VALUE)
{
// SetupDiEnumDeviceInfo
DWORD memberIndex = 0;
SP_DEVINFO_DATA devInfoData;
devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
if (!SetupDiEnumDeviceInfo(
hDeviceInfo,
memberIndex,
&devInfoData))
{
fwprintf(stderr, L"Error on enum: %u\n", GetLastError());
return 1;
}
// SetupDiGetDeviceRegistryProperty
DWORD propertyRetrieved = SPDRP_DEVICEDESC;
DWORD requiredSize;
// First call to get the required size for the buffer
if (!SetupDiGetDeviceRegistryPropertyW(
hDeviceInfo,
&devInfoData,
propertyRetrieved,
NULL,
NULL,
0,
&requiredSize))
{
fwprintf(stderr, L"Error on registry property: %u\n", GetLastError());
return 1;
}
}
else
{
wprintf(L"Error code: %u\n", GetLastError());
return 1;
}
return 0;
}
I have to admit that I am new to C++ and even new to Visual studio. I have to use Visual studio since the rest of the code is in visual studio and want to open a file and then save binary data to it. I have found some help from Visual Studio and found a program which can send strings to a file but I want to send binary data.For this purpose I have amended the program. But the problem is that it is not performing as per expectations and sending some symbols. I know that there are quite a lot of experts on Stack Overflow. Will any body help me in resolving my issue?
#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#include <strsafe.h>
#include<conio.h>
void DisplayError(LPTSTR lpszFunction);
void __cdecl _tmain(int argc, TCHAR *argv[])
//void __cdecl _tmain()
{
HANDLE hFile;
int DataBuffer[5] = { 1, 2, 3, 4, 5 };
DWORD dwBytesToWrite = 5;
DWORD dwBytesWritten = 0;
BOOL bErrorFlag = FALSE;
printf("\n");
if (argc != 2)
{
printf("Usage Error:\tIncorrect number of arguments\n\n");
_tprintf(TEXT("%s <file_name>\n"), argv[0]);
return;
}
hFile = CreateFile(argv[1], // name of the write
GENERIC_WRITE, // open for writing
0, // do not share
NULL, // default security
CREATE_NEW, // create new file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
if (hFile == INVALID_HANDLE_VALUE)
{
DisplayError(TEXT("CreateFile"));
_tprintf(TEXT("Terminal failure: Unable to open file \"%s\" for write.\n"), argv[1]);
return;
}
_tprintf(TEXT("Writing %d bytes to %s.\n"), dwBytesToWrite, argv[1]);
bErrorFlag = WriteFile(
hFile, // open file handle
DataBuffer, // start of data to write
dwBytesToWrite, // number of bytes to write
&dwBytesWritten, // number of bytes that were written
NULL); // no overlapped structure
if (FALSE == bErrorFlag)
{
DisplayError(TEXT("WriteFile"));
printf("Terminal failure: Unable to write to file.\n");
}
else
{
if (dwBytesWritten != dwBytesToWrite)
{
// This is an error because a synchronous write that results in
// success (WriteFile returns TRUE) should write all data as
// requested. This would not necessarily be the case for
// asynchronous writes.
printf("Error: dwBytesWritten != dwBytesToWrite\n");
}
else
{
_tprintf(TEXT("Wrote %d bytes to %s successfully.\n"), dwBytesWritten, argv[1]);
}
}
CloseHandle(hFile);
}
void DisplayError(LPTSTR lpszFunction)
{
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpMsgBuf,
0,
NULL);
lpDisplayBuf =
(LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)
+ lstrlen((LPCTSTR)lpszFunction)
+ 40) // account for format string
* sizeof(TCHAR));
if (FAILED(StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error code %d as follows:\n%s"),
lpszFunction,
dw,
lpMsgBuf)))
{
printf("FATAL ERROR: Unable to output error code.\n");
}
_tprintf(TEXT("ERROR: %s\n"), (LPCTSTR)lpDisplayBuf);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
I want to make a share memory pool for all the other process to share the data, but after I read about the CreateFileMapping API document, I was confused about that it will need to specify the size of the share memory. I actually want it to be dynamic allocate and free which looks more like a service. Is there some way to do the share memory dynamic using createFileMapping or not?
Creating Named Shared Memory.
First Process
The first process creates the file mapping object by calling the CreateFileMapping function with INVALID_HANDLE_VALUE and a name for the object. By using the PAGE_READWRITE flag, the process has read/write permission to the memory through any file views that are created.
Then the process uses the file mapping object handle that CreateFileMapping returns in a call to MapViewOfFile to create a view of the file in the process address space. The MapViewOfFile function returns a pointer to the file view, pBuf. The process then uses the CopyMemory function to write a string to the view that can be accessed by other processes.
Process 1 code:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#define BUF_SIZE 256
TCHAR szName[]=TEXT("Global\\MyFileMappingObject");
TCHAR szMsg[]=TEXT("Message from first process.");
int _tmain()
{
HANDLE hMapFile;
LPCTSTR pBuf;
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
BUF_SIZE, // maximum object size (low-order DWORD)
szName); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not create file mapping object (%d).\n"),
GetLastError());
return 1;
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL)
{
_tprintf(TEXT("Could not map view of file (%d).\n"),
GetLastError());
CloseHandle(hMapFile);
return 1;
}
CopyMemory((PVOID)pBuf, szMsg, (_tcslen(szMsg) * sizeof(TCHAR)));
_getch();
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
return 0;
}
Second Process
A second process can access the string written to the shared memory by the first process by calling the OpenFileMapping function specifying the same name for the mapping object as the first process. Then it can use the MapViewOfFile function to obtain a pointer to the file view, pBuf. The process can display this string as it would any other string. In this example, the message box displayed contains the message "Message from first process" that was written by the first process.
Process 2 code:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#pragma comment(lib, "user32.lib")
#define BUF_SIZE 256
TCHAR szName[]=TEXT("Global\\MyFileMappingObject");
int _tmain()
{
HANDLE hMapFile;
LPCTSTR pBuf;
hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // read/write access
FALSE, // do not inherit the name
szName); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not open file mapping object (%d).\n"),
GetLastError());
return 1;
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL)
{
_tprintf(TEXT("Could not map view of file (%d).\n"),
GetLastError());
CloseHandle(hMapFile);
return 1;
}
MessageBox(NULL, pBuf, TEXT("Process2"), MB_OK);
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
return 0;
}
Source : http://msdn.microsoft.com/en-us/library/windows/desktop/aa366551(v=vs.85).aspx