Canon SDK Initialisation Crash - c++

im currently trying to use the Canon SDK in C++.
It's indeed the first time I use a SDK and im a begginer in C++.
The problem is that when i try to initialize the SDK with the EdsInitializeSDK() function it instantly crash, here is the errors messages :
Exception thrown at 0x00007FFA34E0121C (EDSDK.dll) in CameraTest.exe: 0xC0000005: Access violation reading location 0x00000000B44D4740.
Unhandled exception at 0x00007FFA34E0121C (EDSDK.dll) in CameraTest.exe: 0xC0000005: Access violation reading location 0x00000000B44D4740.
Heres the entire code here :
#include "stdafx.h"
#include "iostream"
#include "EDSDK.h"
#include "EDSDKTypes.h"
#include "CameraModel.h"
#include "CameraModelLegacy.h"
#include "CameraController.h"
#include "CameraEventListener.h"
using namespace std;
int main(void)
{
EdsError err = EDS_ERR_OK;
EdsCameraListRef cameraList = NULL;
EdsUInt32 count = 0;
EdsCameraRef camera = nullptr;
bool isSDKLoaded = false;
err = EdsInitializeSDK();
system("pause");
if (err == EDS_ERR_OK) {
cout << "SDK INITIALISED" << endl;
} else {
cout << "SDK INITIALISATION FAILED WAIT FOR EXIT" << endl;
system("pause");
exit(84);
}
cout << err << endl;
err = EdsGetCameraList(&cameraList);
cout << err << endl;
if (err == EDS_ERR_OK) {
cout << "Camera List Ok" << endl;
err = EdsGetChildCount(cameraList, &count);
cout << "Count : " << count << endl;
if (count == 0) {
err = EDS_ERR_DEVICE_NOT_FOUND;
}
}
else {
cout << "No Camera List" << endl;
}
if (err == EDS_ERR_OK) {
cout << "It worked" << endl;
err = EdsGetChildAtIndex(cameraList, 0, &camera);
} else {
cout << "It didnt worked" << endl;
}
system("pause");
}
If i remove the EDSInitializeSDK function, it don't crash.
Do you have an idea about whats the problem ?
Thanks.

Ok, so the answer is quite simple.
When i connect my camera, a software named "EOS Utility 3" shows up.
Its the problem, when I close it (and makes sure its realy close and not just reducted), it works.
Thanks for your help.
(I was using Canon EDSDK version 3.6.1 with a Canon EOS 1300D)

Related

Why do EnumDomains/NextDomain loop forever?

The following simple code can be directly run in Visual Studio C++ console project.
It will loop forever because the NextDomain will always return the same IUnknown *
According to Microsoft, it should return NULL if the enumeration reaches end. See https://learn.microsoft.com/en-us/dotnet/framework/unmanaged-api/hosting/icorruntimehost-nextdomain-method
However, the NULL is never reached. It seems that it never return the NextDomain but keep returning the same domain.
Is there anything wrong? Thanks.
#include <iostream>
#include <Windows.h>
#include <metahost.h>
#include <mscoree.h>
#pragma comment(lib, "mscoree.lib")
int main()
{
ICLRMetaHost* clrMetaHost = NULL;
ICLRRuntimeInfo* clrRuntimeInfo = NULL;
ICorRuntimeHost* clrCorRuntimeHost = NULL;
do {
if (FAILED(CLRCreateInstance(CLSID_CLRMetaHost, IID_PPV_ARGS(&clrMetaHost))))
{
std::cout << "failed 1" << std::endl;
break;
}
if (FAILED(clrMetaHost->GetRuntime(L"v2.0.50727", IID_PPV_ARGS(&clrRuntimeInfo))))
{
if (FAILED(clrMetaHost->GetRuntime(L"v4.0.30319", IID_PPV_ARGS(&clrRuntimeInfo))))
{
std::cout << "failed 2" << std::endl;
break;
}
}
if (FAILED(clrRuntimeInfo->GetInterface(CLSID_CorRuntimeHost, IID_PPV_ARGS(&clrCorRuntimeHost))))
{
std::cout << "failed 3" << std::endl;
break;
}
if (FAILED(clrCorRuntimeHost->Start()))
{
std::cout << "failed 4" << std::endl;
break;
}
HDOMAINENUM hDomainEnum = nullptr;
if (FAILED(clrCorRuntimeHost->EnumDomains(&hDomainEnum))) {
std::cout << "failed 5" << std::endl;
break;
}
IUnknown* domain;
while (SUCCEEDED(clrCorRuntimeHost->NextDomain(hDomainEnum, &domain))
&& domain != NULL) {
std::cout << "why loop forever here?" << std::endl;
domain->Release();
}
if (FAILED(clrCorRuntimeHost->CloseEnum(hDomainEnum))) {
std::cout << "failed 6" << std::endl;
}
break;
} while (0);
if (clrCorRuntimeHost != NULL) clrCorRuntimeHost->Release();
if (clrRuntimeInfo != NULL) clrRuntimeInfo->Release();
if (clrMetaHost != NULL) clrMetaHost->Release();
return 0;
}
Return code from most enumerators is S_OK to continue and S_FALSE when it did not succeed. S_FALSE is not a fail code.
while (S_OK == clrCorRuntimeHost->NextDomain(hDomainEnum, &domain))
&& domain != NULL) {
std::cout << "why loop forever here?" << std::endl;
domain->Release();
}

Exception thrown at 0x00007FFF168E1657 (vcruntime140d.dll) in "<name>.exe": 0xC0000005: Access violation writing location 0x0000000000000000

I tried creating two different visual c++ console applications for Inter Process Communication(IPC). The Build for both codes is successful.But,when I try to debug it, I get exception like this "Exception thrown at 0x00007FFF168E1657 (vcruntime140d.dll) in FileMapServer_Parent.exe: 0xC0000005: Access violation writing location 0x0000000000000000"
//PARENT PROCESS:
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <Tlhelp32.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <cstring>
#include <cctype>
#include <fstream>
using namespace std
int main()
{
cout << "\t\t.....FILEMAPPING SERVER or PARENT....." << endl;
cout << endl;
//Local Variable Definitions
HANDLE hFileMap;
BOOL bResult;
PCHAR lpBuffer = NULL;
char Buffer[256] = "Hello From File Map Server";
size_t szBuffer = size(Buffer);
// STEP 1 : Create File Map
hFileMap = CreateFileMapping(
INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
256,
L"LOCAL\\MyFileMap);
if (hFileMap == FALSE)
{
cout << "CreateFileMapping Failed & Error Number - " << GetLastError() << endl;
}
else
cout << "CreateFileMapping Success - " << endl;
// STEP 2 : Map View of File
lpBuffer = (PCHAR)MapViewOfFile(
hFileMap,
FILE_MAP_ALL_ACCESS,
0,
0,
256);
if (lpBuffer == NULL)
{
cout << "MapViewOf File Failes & Error No - " << GetLastError() << endl;
}
else
cout << "MapViewOf File Success " << endl;
//STEP 3 : Copy Memory Function
CopyMemory(lpBuffer,Buffer,szBuffer);
//STEP 4 : Unmap View Of File
bResult = UnmapViewOfFile(lpBuffer);
if (bResult == FALSE)
{
cout << "UnMapViewOfFile Failed & Error No - " << GetLastError() << endl;
}
else
cout << "UnMapViewOfFile FSuccess - " << endl;
system("PAUSE");
return 0;
}
Exception while running parent process:
[1]: https://i.stack.imgur.com/bomQB.png
//CHILD PREOCESS:
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <Tlhelp32.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <cstring>
#include <cctype>
#include <fstream>
using namespace std;
int main()
{
cout << "\t\t.....FILEMAPPING CLIENT or CHILD....." << endl;
cout << endl;
// Local Variable Definitions
HANDLE hFileMap;
BOOL bResult;
PCHAR lpBuffer = NULL;
// STEP 1 : OpenFileMapping
hFileMap = OpenFileMapping(
FILE_MAP_ALL_ACCESS,
FALSE,
L"LOCAL\\MyFileMap");
if(hFileMap == NULL)
{
cout << "OpenFileMap Failed & error - " << GetLastError() << endl;
}
else
cout << "OpenFileMap success " << endl;
//STEP 2 : MapViewOfFile
lpBuffer = (PCHAR)MapViewOfFile(
hFileMap,
FILE_MAP_ALL_ACCESS,
0,
0,
256);
if (lpBuffer == NULL)
{
cout << "MapViewOf File Failes & Error No - " << GetLastError() << endl;
}
else
cout << "MapViewOf File Success " << endl;
//STEP 3 : Reading the data from File Map Object
cout << "DATA READING FROM PARENT PROCESS--->" <<lpBuffer<< endl;
//STEP 4 : UnMapViewOfFile
bResult = UnmapViewOfFile(lpBuffer);
if (bResult == FALSE)
{
cout << "UnMapViewOfFile Failed & Error No - " << GetLastError() << endl;
}
else
cout << "UnMapViewOfFile FSuccess - " << endl;
//STEP 5 : Close Handle
CloseHandle(hFileMap);
system("PAUSE");
return 0;
}
The problem is here:
hFileMap = CreateFileMapping(
INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
256,
L"LOCAL\\MyFileMap");
From the documentation of Kernel object namespaces they are case sensitive so you must change LOCAL to Local for this to work.
In addition to the "Global\" prefix, client processes can use the "Local\" prefix to explicitly create an object in their session namespace. These keywords are case sensitive.
https://msdn.microsoft.com/en-us/library/aa382954(v=vs.85).aspx
While debugging this issue I also changed the code to exit if the mapping fails:
if (hFileMap == NULL)
{
cout << "CreateFileMapping Failed & Error Number - " << GetLastError() << endl;
return -1;
}
else
cout << "CreateFileMapping Success - " << endl;
This avoided the crash with the original "LOCAL" (mapping failed).

SDL2 - SDL_AudioSpec audio plays endlessly when not called in while loop

I've made this simple program according to a github code.
All you have to take care of is the while loop at the end of the main() method.
#include "SDL2\SDL.h"
constexpr const char* WAV_PATH = "applause.wav";
#include <iostream>
static Uint8* sg_pAudioPos;
static Uint32 sg_AudioLength;
struct CWavWrapper
{
Uint32 m_Length;
Uint8* m_pBuffer;
SDL_AudioSpec m_Spec;
};
void ExitProgram(int code = 0)
{
system("pause");
exit(code);
}
void AudioCallback(void* pData, Uint8* pStream, int Length);
#undef main
int main()
{
using std::cout;
using std::cerr;
using std::endl;
if (SDL_Init(SDL_INIT_AUDIO) < 0)
{
cerr << "couldnt init audio: " << SDL_GetError() << endl;
ExitProgram(1);
}
cout << "Loading wav... " << WAV_PATH << endl;
static CWavWrapper Wav;
if(SDL_LoadWAV(WAV_PATH,&Wav.m_Spec,&Wav.m_pBuffer,&Wav.m_Length) == NULL)
{
cerr << "couldnt load wav: " << SDL_GetError() << endl;
ExitProgram(1);
}
Wav.m_Spec.callback = AudioCallback;
Wav.m_Spec.userdata = NULL;
sg_pAudioPos = Wav.m_pBuffer;
sg_AudioLength = Wav.m_Length;
cout << "Opening Audio..." << endl;
if (SDL_OpenAudio(&Wav.m_Spec, NULL) < 0)
{
cerr << "couldn't open audio: " << SDL_GetError() << endl;
ExitProgram(1);
}
cout << "Success! Starting Audio..." << endl;
SDL_PauseAudio(0);
while (sg_AudioLength > 0)
{
//If I remove this output line or as in the GitHub example not do the SDL_Delay() the wav gets played infinitely.
//how does printing out a variable change its value (as it should do only in the callback)?
cout << "sg_AudioLength: " << sg_AudioLength << endl;
}
SDL_CloseAudio();
SDL_FreeWAV(Wav.m_pBuffer);
ExitProgram(0);
}
void AudioCallback(void* pData, Uint8* pStream, int Length)
{
if (sg_AudioLength == 0)
return;
if (Length > sg_AudioLength)
{
Length = sg_AudioLength;
}
SDL_MixAudio(pStream, sg_pAudioPos, Length, SDL_MIX_MAXVOLUME);
sg_pAudioPos += Length;
sg_AudioLength -= Length;
}
As you can see at the end of the main() function, I put a description on what happens when I remove the cout line.
I think it might has to do something with the AudioCallback only being called when a certain code is done. But I am not sure and I would like to get an answer to it.
EDIT: I've noticed that when anything gets processed in the while loop, the audio seems to play right. Does anything from compiling to run time notice that the loop does not change the variable and thinks that this is now an endless loop so the loop does not even try to check the variable again?

Win API ReadProcessMemory at base address of DLL returning unexpected data

I'm trying to read the contents of a DLL from memory for some academic research. Specifically, the NTDSA.DLL library for the purpose of mutating specific instructions to simulate programming errors to force the system to fail. The failure will then be recorded to train machine learning algorithms to predict future failures (this is an attempt to generalize previously published research seen here).
I'm getting what I believe to be the base address in virtual memory of the lsass.exe process (which loads the target DLL) through the process outlined here. I'm then calling ReadProcessMemory with an allocated buffer and the handle to lsass obtained by calling OpenProcess with 'PROCESS_ALL_ACCESS' set. The ReadProcessMemory returns with error code 299 80% of the time (partial read) with zero bytes read. My assumption is that the area I'm trying to access is in use when the call is made. Fortunately, it will occasionally return the number of bytes I'm requesting. Unfortunately, the data returned does not match what is on disk when compared to the static DLL in the System32 directory.
So the question is, is ReadProcessMemory doing something funny with the address that I give it, or is my virtual address wrong? Is there another way to figure out where that DLL gets loaded into memory? Any thoughts? Any help or suggestions would be greatly appreciated.
Adding Code:
// FaultInjection.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <psapi.h>
#include <string>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <io.h>
#include <tchar.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[]) {
// Declarations
int pid = 0;
__int64* start_addr;
DWORD size_of_ntdsa;
DWORD aProcesses[1024], cbNeeded, cProcesses;
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
HMODULE hmods[1024];
unsigned int i;
// Get All pids
if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded)){
cout << "Failed to get all PIDs: " << GetLastError() << endl;
return -1;
}
// Find pid for lsass.exe
cProcesses = cbNeeded / sizeof(DWORD);
for (i = 0; i < cProcesses; i++) {
if (aProcesses[i] != 0) {
HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, aProcesses[i]);
if (hProc != NULL) {
HMODULE hMod;
DWORD cbNeededMod;
if (EnumProcessModules(hProc, &hMod, sizeof(hMod), &cbNeededMod)) {
GetModuleBaseName(hProc, hMod, szProcessName, sizeof(szProcessName) / sizeof(TCHAR));
}
if (wstring(szProcessName).find(L"lsass.exe") != string::npos) {
pid = aProcesses[i];
}
CloseHandle(hProc);
}
}
}
cout << "lsass pid: " << pid << endl;
HANDLE h_lsass = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (!h_lsass) {
cout << "Failed to open process (are you root?): " << GetLastError() << endl;
return -1;
}
// Get Process Image File Name
char filename[MAX_PATH];
if (GetProcessImageFileName(h_lsass, (LPTSTR)&filename, MAX_PATH) == 0) {
cout << "Failed to get image file name: " << GetLastError() << endl;
CloseHandle(h_lsass);
return -1;
}
// Enumerate modules within process
if (EnumProcessModules(h_lsass, hmods, sizeof(hmods), &cbNeeded)) {
for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) {
TCHAR szModName[MAX_PATH];
if (GetModuleFileNameEx(h_lsass, hmods[i], szModName, sizeof(szModName) / sizeof(TCHAR))) {
if (wstring(szModName).find(L"NTDSA.dll") != string::npos) {
_tprintf(TEXT("%s\n"), szModName);
MODULEINFO lModInfo = { 0 };
if (GetModuleInformation(h_lsass, hmods[i], &lModInfo, sizeof(lModInfo))){
cout << "\t Base Addr: " << lModInfo.lpBaseOfDll << endl;
cout << "\t Entry Point: " << lModInfo.EntryPoint << endl;
cout << "\t Size of image: " << lModInfo.SizeOfImage << endl;
start_addr = (__int64*)lModInfo.lpBaseOfDll;
size_of_ntdsa = lModInfo.SizeOfImage;
}
else {
cout << "Failed to Print enumerated list of modules: " << GetLastError() << endl;
}
}
} else {
cout << "Failed to Print enumerated list of modules: " << GetLastError() << endl;
}
}
}
else {
cout << "Failed to enum the modules: " << GetLastError() << endl;
}
// Ready to continue?
string cont = "";
cout << "Continue? [Y|n]: ";
getline(cin, cont);
if (cont.find("n") != string::npos || cont.find("N") != string::npos) {
CloseHandle(h_lsass);
return 0;
}
void* buf = malloc(size_of_ntdsa);
if (!buf) {
cout << "Failed to allocate space for memory contents: " << GetLastError() << endl;
CloseHandle(h_lsass);
return -1;
}
SIZE_T num_bytes_read = 0;
int count = 0;
if (ReadProcessMemory(h_lsass, &start_addr, buf, size_of_ntdsa, &num_bytes_read) != 0) {
cout << "Read success. Got " << num_bytes_read << " bytes: " << endl;
} else {
int error_code = GetLastError();
if (error_code == 299) {
cout << "Partial read. Got " << num_bytes_read << " bytes: " << endl;
} else {
cout << "Failed to read memory: " << GetLastError() << endl;
CloseHandle(h_lsass);
free(buf);
return -1;
}
}
if (num_bytes_read > 0) {
FILE *fp;
fopen_s(&fp, "C:\\ntdsa_new.dll", "w");
SIZE_T bytes_written = 0;
while (bytes_written < num_bytes_read) {
bytes_written += fwrite(buf, 1, num_bytes_read, fp);
}
fclose(fp);
cout << "Wrote " << bytes_written << " bytes." << endl;
}
CloseHandle(h_lsass);
free(buf);
return 0;
}
Code works as described minus my amateur mistake of sending the address of the variable I was using to store the address of the location in virtual memory of the target application. In above code, changed:
if (ReadProcessMemory(h_lsass, &start_addr, buf, size_of_ntdsa, &num_bytes_read) != 0) {
to
if (ReadProcessMemory(h_lsass, start_addr, buf, size_of_ntdsa, &num_bytes_read) != 0) {
Works like a charm. Thank you ssbssa for pointing out mistake, sorry for wasting anyone's time.

WriteProcessMemory returns 0 in C++

I am developing a small cash hack for GTA V and I found that when I use
WriteProcessMemory(hp, (LPVOID)0x1417C4C18, &cashVal, (DWORD)sizeof(cashVal), 0)
that the WriteProcessMemory returns 0. Here is the full source code of my small hack.
#include <Windows.h>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int cashVal = 0;
cout << "Enter the amount of cash you want: " << endl;
cin >> cashVal;
HWND hwnd = FindWindow(0, "Grand Theft Auto V");
if (hwnd == 0) {
cout << "Cannot find the GTAV window. Make sure its running in Windowed mode!" << endl;
}
else {
DWORD pid;
GetWindowThreadProcessId(hwnd, &pid);
HANDLE hp = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (!hp) {
cout << "Could not get a handle to GTAV. Try again :(" << endl;
}
else {
int success = WriteProcessMemory(hp, (LPVOID)0x1417C4C18, &cashVal, (DWORD)sizeof
(cashVal), 0);
if (success > 0) {
cout << "You now have " << cashVal << " money!" << endl;
}
else {
cout << "Writing the memory failed!" << endl;
cout << "Error code: " << success << endl;
}
CloseHandle(hp);
}
}
cin.get();
return 0;
}
I basically ask the user to input the cash they want, and it's meant to set it in the game, but it returns a code of 0 and fails. It doesn't fail trying to find the game window because it doesn't print that message to the standard output. Please help me!
NOTE: The hack will be used on single player
First, don't use PROCESS_ALL_ACCESS. Only request what you actually need. WriteProcessMemory() only needs PROCESS_VM_WRITE and PROCESS_VM_OPERATION access, so request only that.
Like many other API functions, when WriteProcessMemory() fails, GetLastError() will tell you why. Your code is assuming that WriteProcessMemory() itself returns an error code directly, but it does not. It returns a BOOL (not an int) to indicate success or failure, and then GetLastError() returns the error code if failure. This is documented behavior:
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is 0 (zero). To get extended error information, call GetLastError. The function fails if the requested write operation crosses into an area of the process that is inaccessible.
Try this:
#include <windows.h>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int cashVal = 0;
cout << "Enter the amount of cash you want: " << endl;
cin >> cashVal;
HWND hwnd = FindWindow(0, "Grand Theft Auto V");
if (hwnd == 0) {
cout << "Cannot find the GTAV window. Make sure its running in Windowed mode!" << endl;
}
else {
DWORD pid;
GetWindowThreadProcessId(hwnd, &pid);
HANDLE hp = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, pid);
if (!hp) {
cout << "Could not get a handle to GTAV. Try again :(" << endl;
}
else {
BOOL success = WriteProcessMemory(hp, (LPVOID)0x1417C4C18, &cashVal, sizeof(cashVal), 0);
if (success) {
cout << "You now have " << cashVal << " money!" << endl;
}
else {
DWORD errCode = GetLastError();
cout << "Writing the memory failed!" << endl;
cout << "Error code: " << errCode << endl;
}
CloseHandle(hp);
}
}
cin.get();
return 0;
}
You are most likely trying to write to a memory path where you don't have access to... probably you are using a 32-bit program to write to a 64-bit memory address(that's if u use a 64-bit computer), I think I had this problem a few years back porting solved my problem then forgive me if I am wrong atleast that was what I thought.
Try the code on a 32-bit address and if it works... that solves your problem.
And for the Getting_Last_Error you can add this lil' bit of functionality I use.
void PrintLastErrorMsg(){
LPTSTR pTmp = NULL;
DWORD errnum = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ARGUMENT_ARRAY,
NULL,
errnum,
LANG_NEUTRAL,
(LPTSTR)&pTmp,
0,
NULL
);
cout << "Error(" << errnum << "): " << pTmp << endl;
}
Be free to make changes.