Spaces in system() C++ - c++

I've tried with some solutions found in Stackoverflow, but i can't get it to work, i want to start a .LOG (.txt file) from C++, but the path folder containing it might have spaces, so when i try to start it, i get an error saying it cant find the file because the pah (containing spaces) is wrong, here is what my code looks like:
void Log (unsigned int Code,...)
{
char currdate[11] = {0};
SYSTEMTIME t;
GetLocalTime(&t);
sprintf(currdate, "%02d:%02d:%02d", t.wHour, t.wMinute, t.wSecond);
PROCESSENTRY32 pe32;
FILE* FileHwnd1;
FileHwnd1 = fopen("TEST.log","a+");
fprintf(FileHwnd1,"[%s] Code: %X\n",currdate,Code);
fclose(FileHwnd1);
char buffer[MAX_PATH];
GetModuleFileName( NULL, buffer, MAX_PATH);
char Path[50];
wsprintf(Path,"start %s\\AntiHack.log",buffer);
system(Path);//Here is where i get the containing spaces path error
}
Thanks.

I would advise you avoid the system call entirely and do the process launch yourself.
Use AssocQueryString() to find the associated process for your
extension (in this case, .log)
Setup and launch a CreateProcess() call to invoke, passing the
appropriate command line.
there are other ways to do this, but as you're noticing now, going a round-about way will always have pitfalls. The above is spot-on with how Explorer.exe launches the associated process for an extension.

You can try:
wsprintf(Path,"start \"\" \"%s\"\\\AntiHack.log",buffer);

Related

Finding where a handle is open to

I'm messing around with handles / hooks, and have a question. Right now, I have a DLL that I inject into the process that I'm playing with. The DLL hooks the CloseHandle() function. When CloseHandle is called, I do the following:
int WINAPI DetourCloseHandle(HANDLE hObject)
{
OutputDebugStringA("CLOSE HADNLE");
char name[MAX_PATH];
GetFinalPathNameByHandle(hObject, name, MAX_PATH, FILE_NAME_NORMALIZED);
OutputDebugStringA(name);
return oCloseHandle(hObject);
}
My goal in this is to figure out where the handle is open to, and if the handle is open to a certain process, then use the handle to read that processes memory. What gets printed out when CloseHandle is called is usually paths to random files that the application reads, but I also noticed random ASCII characters being printed at times, as the "Name" of where the handle is opened to. This can be seen here.
Sometimes I also notice paths to certain .exe files. This is not unusual, as the application that I'm injecting into does read / look at binary files. My question is, when I see the "name" returned from GetFinalPathNameByHandle as the path to an exe file, how do I know if the handle is opened to the binary file itself, or if the handle file is opened to the actual running process with that name.
I would also like some insight as to what the ASCII characters that are being printed are. Thanks!
For the random data print you pasted, it likely was because it is just uninitialized garbage in name array, you should always check GetFinalPathNameByHandle's return value before do something with name:
DWORD ret = GetFinalPathNameByHandle(hObject, name, MAX_PATH, FILE_NAME_NORMALIZED);
if (ret) {
OutputDebugStringA(name);
} else {
OutputDebugStringA("GetFinalPathNameByHandle");
// check GetLastError()
}
Also, note that GetFinalPathNameByHandle thake the string as TCHAR strings, and you are print it via OutputDebugStringA. So I would suggest either use the ANSI version GetFinalPathNameByHandleA, or use TCHAR name[MAX_PATH]; and print with OutputDebugString instead.

Open .chm file at specific page/topic using command line arguments

I am attempting to open a .chm file(A windows help file) at a specific page/topic by using a system call in C++.
I can successfully open the .chm file to the start page through the following code, but how can I open a .chm file to a specific page/topic inside the help file?
system("start c:/help/myhelp.chm");
PS: I know system is evil/discouraged but the system part is not really relevant its the command line arguments I pass with the .chm file(that will specify what page I want to open) that I am trying to determine.
Ok the arguments are like so:
system(" /Q /E:ON /C HH.EXE ms-its:myChm.chm::myPageName.htm");
There is an API in the Windows SDK called HtmlHelp in the HtmlHelp.h file. You can call like so:
HtmlHelp(GetDesktopWindow(), L"C:\\helpfile\\::/helptopic.html", HH_DISPLAY_TOPIC, NULL);
The Microsoft Docs - HtmlHelpA function provides more information about the function. HtmlHelp() will normally resolve to HtmlHelpA() or HtmlHelpW() depending on whether Unicode compiler option is set or not.
See as well Microsoft Docs - HTML Help API Overview.
Another option - use ShellExecute. The Microsoft help is not easy to use. This approach is much easier and in line with your question. Here is a quick routine to open a help file and pass an ID number. I have just set up some simple char’s so you can see what is going on:
void DisplayHelpTopic(int Topic)
{
// The .chm file usually has the same name as the application - if you don’t want to hardcode it...
char *CmndLine = GetCommandLine(); // Gets the command the program started with.
char Dir[255];
GetCurrentDirectory (255, Dir);
char str1[75] = "\0"; // Work string
strncat(str1, CmndLine, (strstr(CmndLine, ".exe") - CmndLine)); // Pull out the first parameter in the command line (should be the executable name) w/out the .exe
char AppName[50] = "\0";
strcpy(AppName, strrchr(str1, '\\')); // Get just the name of the executable, keeping the '\' in front for later when it is appended to the directory
char parms[300];
// Build the parameter string which includes the topic number and the fully qualified .chm application name
sprintf(parms,_T("-mapid %d ms-its:%s%s.chm"), Topic, Dir, AppName);
// Shell out, using My Window handle, specifying the Microsoft help utility, hh.exe, as the 'noun' and passing the parameter string we build above
// NOTE: The full command string will look like this:
// hh.exe -mapid 0 ms-its:C:\\Programs\\Application\\HelpFile.chm
HINSTANCE retval = ShellExecute(MyHndl, _T("open"), _T("hh.exe"), parms, NULL, SW_SHOW);
}
The topics are numbered within your .chm file. I set up a #define for each topic so if I had to change the .chm file I could just change the include file to match and not have to worry about searching through the code for hardcoded values.

C++: How to make a my program open a .exe with optional args

I'm having some trouble with a program. My goal is to have it open several .exe files with optional args passed. For example if I wanted to open up a pdf I could type the string below into a cmd window.
// If used in a cmd window it will open up my PDF reader and load MyPDF.pdf file
"c:\Test space\SumatraPDF.exe" "c:\Test space\Sub\MyPDF.pdf"
Here are two tries I used. The first opens the PDF but of course doesn't load the file. The second simply doesn't work.
// Opens the PDF in my program
system("\"C:\\Test space\\SumatraPDF.exe\"");
// Error I get inside of a cmd window is the comment below
// 'C:\Test' is not recognized as an internal or external command, operable program or batch file.
//system("\"C:\\Test space\\SumatraPDF.exe\" \"C:\\Test space\\Sub\\MyPDF.pdf\"");
I'm unsure of the reason why the second one does not work. It could be I'm misunderstanding something about system, or I'm not using delimiters right.
I feel like there is a library out there designed for this rather than creating a long string that uses so many delimiters.
Thanks for any help.
Welcome to Stack Overflow!
The system method works by passing it's argument to cmd /c. So you will need an extra set of quotes around it. See related question posted by sled.
As an alternative to system, take a look at the ShellExecute or ShellExecuteEx Win32 API function. It has more features although it is not as portable.
// ShellExecute needs COM to be initialized
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
SHELLEXECUTEINFO sei = {0};
sei.cbSize = sizeof(sei);
sei.lpFile = prog; // program like c:\Windows\System32\notepad.exe
sei.lpParameters = args; // program arguments like c:\temp\foo.txt
sei.nShow = SW_NORMAL; // app should be visible and not maximized or minimized
ShellExecuteEx(&sei); // launch program
CoUninitialize();
More information here.

How to find the parent exe of a dll from inside the dll?

I need to do some stuff in a dll based on which process has loaded it. So being relatively new to windows programming I need help figuring out how to find the exe which loaded the current dll. So far I have been hard coding the exe file name, which is the dumbest thing to do :D
1) Some one suggested using GetModuleFileName() function. But this seems to crash my app.(I used 0 as the module handle). I am doing nothing fancy. I used the following syntax
GetModuleFileName(0,&fileName,MAX_PATH)
EDIT: I understood from here that I cannot get the .exe name with this call as it returns only the dll name :(
2)Is it a good idea to do this in the DllMain ?? I know that DllMain is not the place to do complicated stuff. I also understand loader lock related issues.All I need is to find the name of the parent process.
I appreciate your time !
ADD: I tried to use GetProcessImageFileName after getting the parent process ID. I get an access violation error. When I tried to debug I noticed that the openProcess call leaves my result argument(image file path-LPTSTR) as a bad pointer.
Error code 87-INVALID PARAMETER is returned by the GetProcessImageFileName call.
But the current process id is a valid id.
Here is the code
LPTSTR fileName={0};
HANDLE hP=OpenProcess(PROCESS_QUERY_INFORMATION ,FALSE, processes[i]) ;
GetProcessImageFileName(hP,fileName,(DWORD)MAX_PATH+1);
What Am I doing wrong??
Thanks
EDIT IMPORTANT:
I found out that I am trying to use openprocess on an idle process. (i.e) I forgot that my parent process could possibly be waiting idle for me since I sync it . So now I got the bad news that I cannot open an idle process using OpenProcess. How else can i get to look into the object of an Idle process?? (I know for sure its idle because I could not find it in the snapshot. I had to use enumerateprocess to locate its id; But i do use normal process enumeration from the snapshot to find the parent process id in the first place)
If you have declared your fileName variable as something like char fileName or char fileName[MAX_PATH], you may receive an error because your parameter is incorrect: you use the address of the variable (though, you don't specify whether it is a compile time error or runtime error, you say it crashes your app, so I go with Richard here, you've not allocated your variable).
I tried the following code, which works both from within a DLL (it gets the name of the executable, not the DLL module) or from within the executable itself.
(Note: code updated based on Remy's comments below, thanks)
WCHAR exePath[MAX_PATH + 1];
DWORD len = GetModuleFileNameW(NULL, exePath, MAX_PATH);
if (len > 0) {
wcout
<< L"Exe path"
<< (len == MAX_PATH) ? L" (truncated):" : L":"
<< exePath
<< endl;
} else {
wcout
<< L"Error getting exe path: "
<< GetLastError()
<< endl;
}
Note: if the buffer is not large enough, GetModuleFileName will truncate the result and return nSize.
More on handling filenames in Win32.
Refer the following link to know about the syntax and the detailed description about the GetModuleFileName()
Steps to do:
First get the full path of the executable file using the code:
TCHAR szEXEPath[2048];
char actualpath[2048];
GetModuleFileName ( NULL, szEXEPath, 2048 );
for(int j=0; szEXEPath[j]!=0; j++)
{
actualpath[j]=szEXEPath[j];
}
From the full path of the executable file, split the string to get only the executable name using the built in function str.find_last_of()
std::string str (actualpath);
std::size_t found = str.find_last_of("/\\");
std::cout<< str.substr(found+1) << '\n';
Now you can get only the executable file name.
I assume you are coding in C. You most likely have not allocated MAX_PATH + 1 characters for filename.

Trouble restarting exe

I need to restart the program that im working on after an update has been downloaded except im running into some issues.
If i use CreateProcess nothing happens, if i use ShellExecute i get an 0xC0150002 error and if i use ShellExecute with the command "runas" it works fine. I can start the command prompt fine using CreateProcess and ShellExecute just not the same exe again and dont want to use runas as this will elevate the exe.
Any Ideas?
Windows 7, visual studio 2008 c++
alt text http://lodle.net/shell_error.jpg
CreateProcess:
char exePath[255];
GetModuleFileName(NULL, exePath, 255);
size_t exePathLen = strlen(exePath);
for (size_t x=exePathLen; x>0; x--)
{
if (exePath[x] == '\\')
break;
else
exePath[x] = '\0';
}
char name[255];
GetModuleFileName(NULL, name, 255);
PROCESS_INFORMATION ProcInfo = {0};
STARTUPINFO StartupInfo = {0};
BOOL res = CreateProcess(name, "-wait", NULL, NULL, false, 0, NULL, exePath, &StartupInfo, &ProcInfo );
ShellExecute:
char exePath[255];
GetModuleFileName(NULL, exePath, 255);
size_t exePathLen = strlen(exePath);
for (size_t x=exePathLen; x>0; x--)
{
if (exePath[x] == '\\')
break;
else
exePath[x] = '\0';
}
char name[255];
GetModuleFileName(NULL, name, 255);
INT_PTR r = (INT_PTR)ShellExecute(NULL, "runas", name, "-wait", exePath, SW_SHOW);
CreateProcess() is an arcane beast. I remember unfondly my first frustrations with it. You should look at the Microsoft CreateProcess Example and the CreateProcess Page. (those links likely have a short lifetime, Googling CreateProcess should work just as well).
I can see 3 problems in your code.
StartupInfo must have "cb" set to the structure size:
STARTUPINFO StartupInfo = {0};
StartupInfo.cb = sizeof(StartupInfo);
The second argument requires both the command and the arguments to form the command line. Your program will see "-wait" as argv[0] and ignore it or pay it no mind.
char command[512];
sprintf(command, "%s -wait", name);
BOOL res = CreateProcess(name, command, // and as you had before
You don't look at GetLastError() if CreateProcess() fails (by returning a zero). It may have helped you but I suspect it would just say "invalid argument" or somesuch. Hey, there's only 10 of them to check, don't be lazy :-)
Another bug I committed is not closing the hProcess and/or hThread handles return in PROCESS_INFORMATION when I was done. I did do hProcess, but not hThread.
Looks like a manifest or registry question judging from the error code. If you can't get the actual error message string for more details, you might try:
moving every possible manifest file (Microsoft.VC80.CRT.manifest and the like) into your exe's directory, to ensure accessibility
cleanly and completely uninstall/wipe out old versions of DLL you may have installer newer versions of (I suggest: uninstall EVERY version, clean the registry with a sweep-clean tool such as Norton's, reinstall the new stuff from scratch)
What happens if you run the process using system()? It gives you less control, but you'll be running it from the same context you're running in. Also, Try monitoring the launch of your second process using ProcMon, it might give you the hint you need about the source of the failure.
Ok worked it all out in the end.
The first time my exe ran it used the default paths and as such loaded vld (a leak detector dll) from the default path. However in the exe i modified the dll path to be the bin folder ([app]\bin) when i restarted the exe using CreateProcess it picked up on a different vld dll (this was my mistake) that had incorrect side by side linkage and it was only after looking at event viewer that i worked it out.
Thanks for all your help.