Problems with opening a process with DEBUG flags - c++

I'm trying to open a process with my debugger using CreateProcess with the DEBUG_PROCESS and DEBUG_ONLY_THIS_PROCESS flags and the the process is opened, but then when I try to call SymInitialize with the handle I receive, it fails.
This is my code:
#include <windows.h>
#include <stdio.h>
#include <dbghelp.h>
#pragma (lib, "dbghelp.lib");
bool EnablePrivilege(LPCTSTR lpszPrivilegeName, BOOL bEnable)
{
HANDLE hToken;
TOKEN_PRIVILEGES tp;
LUID luid;
bool ret;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_READ, &hToken))
return FALSE;
if (!LookupPrivilegeValue(NULL, lpszPrivilegeName, &luid))
return FALSE;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : 0;
ret = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL);
CloseHandle(hToken);
return ret;
}
void main()
{
EnablePrivilege(SE_DEBUG_NAME, TRUE);
STARTUPINFOA startInfo;
PROCESS_INFORMATION processInfo;
ZeroMemory( &startInfo, sizeof(startInfo) );
startInfo.cb = sizeof(startInfo);
ZeroMemory( &processInfo, sizeof(processInfo) );
DWORD creationFlags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION;
const char* comLine = "Some process path and name";
// Start the child process.
if( CreateProcessA( NULL, // No module name (use command line)
(LPSTR)comLine, //argv[1], // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
creationFlags, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&startInfo, // Pointer to STARTUPINFO structure
&processInfo ) // Pointer to PROCESS_INFORMATION structure
== false )
{
printf("FAIL!");
return;
}
SetLastError(0);
bool ok = SymInitialize(processInfo.hProcess, NULL, true);
int err = GetLastError();
}
If I call CreateProcess with no creation flags, symInitialize succeed.
What am I doing wrong?

Your error is result of calling MAKE_HRESULT macro as
MAKE_HRESULT(ERROR_SEVERITY_ERROR, FACILITY_NULL, ERROR_INVALID_DATA)
So your error code is not trash. Documentaion doesn't say what kind of data might be invalid in this context. I will try to see what exactly is causing the problem.
EDIT:
This code works for me
#include <windows.h>
#include <stdio.h>
#include <dbghelp.h>
#include <WinError.h>
bool EnablePrivilege(LPCTSTR lpszPrivilegeName, BOOL bEnable)
{
HANDLE hToken;
TOKEN_PRIVILEGES tp;
LUID luid;
bool ret;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_READ, &hToken))
return FALSE;
if (!LookupPrivilegeValue(NULL, lpszPrivilegeName, &luid))
return FALSE;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : 0;
ret = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL);
CloseHandle(hToken);
return ret;
}
void main()
{
EnablePrivilege(SE_DEBUG_NAME, TRUE);
STARTUPINFOA startInfo;
PROCESS_INFORMATION processInfo;
ZeroMemory( &startInfo, sizeof(startInfo) );
startInfo.cb = sizeof(startInfo);
ZeroMemory( &processInfo, sizeof(processInfo) );
DWORD creationFlags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION;
const char* comLine = "C:\\Windows\\Notepad.exe";
// Start the child process.
if( CreateProcessA( NULL, // No module name (use command line)
(LPSTR)comLine,// argv[1], // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
creationFlags, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&startInfo, // Pointer to STARTUPINFO structure
&processInfo ) // Pointer to PROCESS_INFORMATION structure
== false )
{
printf("FAIL!");
return;
}
SetLastError(0);
bool ok = SymInitialize(processInfo.hProcess, NULL, true);
HRESULT err = HRESULT_FROM_WIN32(GetLastError());
}
I don't know why it doesn't for you - I am running windows XP, it might be a difference. For me SymInitialize returns true, and GetLastError returns 0x800700cb, which means only that it didn't found evirnment variable pointing it to directory with symbol files.
This might be stupid question, but perhaps you are missing some debugging libraries in your system? Have you tried installing eg. Debugging Tools for
Windows? I would reccomend 'Download Debugging Tools from the Windows SDK' option - read the description. I guess every programming IDE around would install it for you or have you install it before debugging anything, but it's always best to check.

When process is just created with DEBUG_PROCESS flag no symbols are loaded. It is required to wait for some LOAD_DLL_DEBUG_EVENT and then call SymInitialize().

Related

Running an interactive application with elevated privileges within a Standard User

I am trying to open an interactive application running under the SYSTEM account within the desktop of a standard user(The interactive application has Administrative Privileges). I know this is generally not possible due to session isolation etc. However, I have witnessed applications which does so.
#pragma comment(lib, "advapi32.lib")
using namespace std;
STARTUPINFO GetStartupInfo()
{
STARTUPINFO startupInfo;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = const_cast<LPWSTR>(_T("Winsta0\\default"));
startupInfo.dwFlags = STARTF_USESHOWWINDOW;
startupInfo.wShowWindow = SW_SHOW;
return startupInfo;
}
HANDLE SetInfoOnToken(HANDLE existingToken)
{
HANDLE duplicateToken;
DWORD TokenSessionId = 1;
DuplicateTokenEx(existingToken, MAXIMUM_ALLOWED, nullptr, SECURITY_IMPERSONATION_LEVEL::SecurityIdentification, TOKEN_TYPE::TokenPrimary, &duplicateToken);
SetTokenInformation(duplicateToken, TOKEN_INFORMATION_CLASS::TokenSessionId, &TokenSessionId, sizeof(TokenSessionId));
return duplicateToken;
}
bool SetTcbPrivilege(HANDLE hToken)
{
TOKEN_PRIVILEGES tp;
LUID luid;
bool success = LookupPrivilegeValue(NULL, _T("SeTcbPrivilege"), &luid);
if (!success) {
wcout << GetLastError();
return false;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(&hToken,FALSE,&tp,sizeof(TOKEN_PRIVILEGES),
(PTOKEN_PRIVILEGES)NULL,(PDWORD)NULL))
{
printf("AdjustTokenPrivileges error: %u\n", GetLastError());
return false;
}
if (GetLastError() == ERROR_NOT_ALL_ASSIGNED) return false;
}
int _tmain(int argc, TCHAR *argv[], TCHAR *envp[])
{
wstring processName = _T("notepad.exe");
TCHAR* name = (wchar_t*)processName.c_str();
DWORD sessionId = 0;
STARTUPINFO startupInfo = GetStartupInfo();
PROCESS_INFORMATION processInformation;
HANDLE processHandle = nullptr;
ZeroMemory(&processInformation, sizeof(processInformation));
HANDLE hToken = GetCurrentProcessToken();
SetTcbPrivilege(hToken);
hToken = SetInfoOnToken(hToken);
bool success = false;
success = CreateProcessAsUser(hToken, nullptr, name, nullptr, nullptr, false, 0, nullptr, nullptr, &startupInfo, &processInformation);
if (success)
{
wcout << "Process started.\n";
}
else
{
wcout << "There was a problem starting the process.\n";
wcout << GetLastError();
return 0;
}
CloseHandle(processInformation.hProcess);
CloseHandle(processInformation.hThread);
return 0;
}
This code works perfectly when started normally. But when run under the SYSTEM account, it does not show the notepad window (I am aware it generally shouldn't, but that is the limitation I am trying to overcome and have seen certain apps doing so). There is however a process for notepad listed in the Task Manager.
What am I missing in the code which returns this unexpected behavior ? I am left with less samples of such scenario, so please provide any suggestions on this.
EDIT:
At this point the process does not run an leaves an ERROR_INVALID_HANDLE error. What am I doing incorrect ? Please suggest.

How to execute commands from an attached console

I'm coding a WinAPI GUI program that needs calling ftp and possibly other console programs while getting their console output to act accordingly ie. waiting for ftp to complete execution before reading all its output wouldn't do.
My current approach is calling CreateProcess() to create a cmd.exe process potentially hiding the ugly console window, AttachConsole() to make it my own, GetStdHandle() to get input and output handles, SetConsoleCursorPosition() to the end of the console buffer, and WriteConsole() with commands such as ftp\n or dir\n. Yet this commands are written but not executed. However, I can manually use the same console ( using CreateProcess() with CREATE_NEW_CONSOLE flag ) to type ftp press enter and get it executed.
Previous approaches involved:
Calling ftp directly with CreateProcess() and redirected inputs/outputs.
Couldn't get ftp output until the CreateProcess() process had already ended.
Using system().
Was advised against its usage before getting any output.
My current stripped down code:
// Next two structures might be a bit misleading, they were used for the 1. previous
// approach
PROCESS_INFORMATION piProcInfo;
ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION));
STARTUPINFO siStartInfo;
ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = g_hChildStd_OUT_Wr;
siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
siStartInfo.hStdInput = g_hChildStd_IN_Rd;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
SECURITY_ATTRIBUTES security;
security.nLength = sizeof(SECURITY_ATTRIBUTES);
security.lpSecurityDescriptor = NULL;
security.bInheritHandle = FALSE;
CreateProcess( NULL, "cmd", &security, &security, FALSE, NORMAL_PRIORITY_CLASS |
CREATE_NEW_CONSOLE, NULL, NULL, &siStartInfo, &piProcInfo);
uint32_t pidConsole = piProcInfo.dwProcessId;
while ( ! AttachConsole(pidConsole) ){};
HANDLE myConsoleIn, myConsoleOut;
myConsoleIn = GetStdHandle(STD_INPUT_HANDLE);
myConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
Sleep(100);
CONSOLE_SCREEN_BUFFER_INFO myConsoleCursorInformation = {};
GetConsoleScreenBufferInfo(myConsoleOut,&myConsoleCursorInformation);
SetConsoleCursorPosition(myConsoleOut,myConsoleCursorInformation.dwSize);
CHAR myConsoleBuffer[200]="dir\n";
DWORD myConsoleProcessed;
WriteConsole( myConsoleOut, myConsoleBuffer, 4, &myConsoleProcessed, NULL);
How can I get a command written in the console to execute? Is there an alternative to my attempt of ending commands with a trailing \n ie. using WriteConsole() with a dir\n or ftp\n argument.
I thought about sending a keypress to the process in question after typing the desired command. Yet the created console needs not only to manually press the enter key but also having dir, ftp or whatever command to be manually typed.
Please feel free to point out any missing information !
How can I get a command written in the console to execute? Is there an
alternative to my attempt of ending commands with a trailing \n ie.
using WriteConsole() with a dir\n or ftp\n argument.
Try the following code to see if it works:
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
const wchar_t *cmdPath = L"C:\\Windows\\System32\\cmd.exe";
wchar_t *cmdArgs = (wchar_t *)L"C:\\Windows\\System32\\cmd.exe /k dir";
BOOL result = CreateProcess(cmdPath, cmdArgs, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
DWORD errCode = GetLastError();
if (!result)
{
std::cout << "Create Process failed: " << GetLastError() << std::endl;
}
/K Run Command and then return to the CMD prompt.
This is useful for testing, to examine variables
Use /C if you want "Run Command and then terminate".
Update: Complete code for communicating with a child process(cmd.exe) using pipes.
HANDLE g_hChildStd_IN_Rd = NULL;
HANDLE g_hChildStd_IN_Wr = NULL;
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
#define BUFSIZE 1024
void ErrorExit(LPCTSTR 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) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(1);
}
void ReadFromPipe(void)
{
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
for (;;)
{
DWORD bytesAvail = 0;
if (!PeekNamedPipe(g_hChildStd_OUT_Rd, NULL, 0, NULL, &bytesAvail, NULL)) {
std::cout << "Failed to call PeekNamedPipe" << std::endl;
}
if (bytesAvail) {
DWORD n;
BOOL success = ReadFile(g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &n, NULL);
if (!success || n == 0) {
}
bSuccess = WriteFile(hParentStdOut, chBuf,n, &dwWritten, NULL);
}
else
{
break;
}
}
}
void WriteToPipe(void)
{
DWORD dwWritten;
BOOL bSuccess = FALSE;
CHAR buf[] = "dir\n";
bSuccess = WriteFile(g_hChildStd_IN_Wr, buf, sizeof(buf)-1, &dwWritten, NULL);
}
int main()
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES saAttr;
printf("\n->Start of parent execution.\n");
// Set the bInheritHandle flag so pipe handles are inherited.
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Create a pipe for the child process's STDOUT.
if (!CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0))
ErrorExit(TEXT("StdoutRd CreatePipe"));
// Ensure the read handle to the pipe for STDOUT is not inherited.
if (!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0))
ErrorExit(TEXT("Stdout SetHandleInformation"));
// Create a pipe for the child process's STDIN.
if (!CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0))
ErrorExit(TEXT("Stdin CreatePipe"));
// Ensure the write handle to the pipe for STDIN is not inherited.
if (!SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0))
ErrorExit(TEXT("Stdin SetHandleInformation"));
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
si.cb = sizeof(STARTUPINFO);
si.hStdError = g_hChildStd_OUT_Wr;
si.hStdOutput = g_hChildStd_OUT_Wr;
si.hStdInput = g_hChildStd_IN_Rd;
si.dwFlags |= STARTF_USESTDHANDLES;
TCHAR cmdPath[] = TEXT("C:\\Windows\\System32\\cmd.exe");
BOOL result = CreateProcess(cmdPath, NULL, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
DWORD errCode = GetLastError();
if (!result)
{
std::cout << "Create Process failed: " << GetLastError() << std::endl;
}
for (;;)
{
ReadFromPipe();
WriteToPipe();
}
}

Communicating with PuTTY via pipe

I want to capture PuTTY's STDIN and STDOUT pipes. So I open putty.exe via CreateProcess with passing created pipes but I can't read anything from pipes. My code works when I run a bat file.
How can I accomplish this?
Thanks
//This code is from MSDN and I edited it a little
#include <QCoreApplication>
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#pragma comment(lib, "user32.lib")
#define BUFSIZE 4096
HANDLE g_hChildStd_IN_Rd = NULL;
HANDLE g_hChildStd_IN_Wr = NULL;
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
HANDLE g_hInputFile = NULL;
void CreateChildProcess(void);
void WriteToPipe(void);
void ReadFromPipe(void);
void ErrorExit(PTSTR);
int main(int argc, char *argv[])
{
SECURITY_ATTRIBUTES saAttr;
// Set the bInheritHandle flag so pipe handles are inherited.
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Create a pipe for the child process's STDOUT.
if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) )
ErrorExit((PTSTR)TEXT("StdoutRd CreatePipe"));
// Ensure the read handle to the pipe for STDOUT is not inherited.
if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) )
ErrorExit((PTSTR)TEXT("Stdout SetHandleInformation"));
// Create a pipe for the child process's STDIN.
if (! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0))
ErrorExit((PTSTR)TEXT("Stdin CreatePipe"));
// Ensure the write handle to the pipe for STDIN is not inherited.
if ( ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
ErrorExit((PTSTR)TEXT("Stdin SetHandleInformation"));
// Create the child process: putty
CreateChildProcess();
// read from pipe and printf incoming data
ReadFromPipe();
}
// Read output from the child process's pipe for STDOUT
// and write to the parent process's pipe for STDOUT.
// Stop when there is no more data.
void ReadFromPipe(void)
{
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
for (;;)
{
bSuccess = ReadFile( g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL);
if( ! bSuccess || dwRead == 0 )
break;
printf("received hex:\n");
for (int i = 0; i < dwRead; i++)
{
printf("%02X", chBuf[i]);
}
printf("\nactual string: %s\n",chBuf);
}
}
void CreateChildProcess()
// Create a child process that uses the previously created pipes for STDIN and STDOUT.
{
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
BOOL bSuccess = FALSE;
// Set up members of the PROCESS_INFORMATION structure.
ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
// Set up members of the STARTUPINFO structure.
// This structure specifies the STDIN and STDOUT handles for redirection.
ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = g_hChildStd_OUT_Wr;
siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
siStartInfo.hStdInput = g_hChildStd_IN_Rd;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
// Create the child process.
bSuccess = CreateProcess(L"E:\\putty.exe",
NULL, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
// If an error occurs, exit the application.
if ( ! bSuccess )
ErrorExit((PTSTR)TEXT("CreateProcess"));
else
{
// Close handles to the child process and its primary thread.
// Some applications might keep these handles to monitor the status
// of the child process, for example.
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
}
}
// Format a readable error message, display a message box,
// and exit from the application.
void ErrorExit(PTSTR 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)*sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(1);
}
PuTTY is a GUI application. You cannot communicate with it using input/output redirection.
Use plink.exe from PuTTY package. It's a console application with the same set of command-line arguments and features as PuTTY.
Though even better, using some C++ SSH library instead.
I found out that PuTTY doesn't have pipe for this purpose and since I didn't want to use plink, I modified PuTTY's source code and embedded pipe in it. Now it works as I want.

CreateProcess can not run a application

I just want to create a process to run a application on windows my code as below:
//init the structure
STARTUPINFOW StartupInfo;
ZeroMemory(&StartupInfo,sizeof(StartupInfo));
StartupInfo.cb = sizeof(StartupInfo);
StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow = true ;
PROCESS_INFORMATION ProcessInfo;
ZeroMemory(&ProcessInfo,sizeof(ProcessInfo));
DWORD dwExitCode = 0;
LPCWSTR cmdFormat = "xxxxxx"; // this is the applocation's path
LPWSTR cmd = new wchar_t[256*sizeof(wchar_t)];
wcscpy_s(cmd, wcslen(cmdFormat)+1,cmdFormat);
int ret = CreateProcessW(cmd,
NULL,
NULL,
NULL,
false,
NORMAL_PRIORITY_CLASS,
NULL,
NULL,
&StartupInfo,
&ProcessInfo);
if(ret)
{
CloseHandle(ProcessInfo.hThread);
WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);
CloseHandle(ProcessInfo.hProcess);
}
if(dwExitCode==0)
{
DWORD errorcode = GetLastError();
std::cout<<"ERROR: "<<errorcode<<std::endl;
}
I use this function that I can create new process to run notepad.exe and some other applications
Q1: but when I close the application the dwExitCode = 0 and the errorcode 1803
Q2: some application can not run just exit immediately
Following function always works for me:
static int createProcess(string cmdLine, bool isWait, LPDWORD pExitCode)
{
STARTUPINFOA si;
PROCESS_INFORMATION pi;
::ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
::ZeroMemory(&pi, sizeof(pi));
// reset last error
::SetLastError(0);
// Start the child process.
BOOL bCreateProcess = ::CreateProcessA(NULL, // No module name (use command line)
(LPSTR) cmdLine.c_str(), // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
CREATE_NO_WINDOW, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi); // Pointer to PROCESS_INFORMATION structure
if(!bCreateProcess)
{
// create process failed,
//Logger::trace(error, getClassName(), "createProcess", getFormattedStringA("create process failed with error:%d, Commad line:'%s',isWait:%d",GetLastError(), cmdLine.c_str(), isWait),"CreateProcess Failed");
return 0;
}
//Logger::trace(info, getClassName(), "createProcess", getFormattedStringA("created process,Commad line:'%s',isWait:%d,Result:%d", cmdLine.c_str(), isWait,bCreateProcess),"Launched Process");
// Wait until child process exits.
if(isWait)
{
::WaitForSingleObject(pi.hProcess, INFINITE);
if(pExitCode)
{
::GetExitCodeProcess(pi.hProcess, pExitCode);
}
}
::CloseHandle( pi.hProcess );
pi.hProcess = NULL;
::CloseHandle( pi.hThread );
pi.hThread = NULL;
return 1; // return non zero. function succeeded
}
Yes I find the root cause some application need some local resource ,so maybe need the parent's starting directory

Cannot read from pipe in separate thread from suspended process

I am trying to create process with CreateProcess in suspended state and the read from it's stdout. For base I took MSDN code.
After creating process I'm going to set Job restrictions(not implemented yet) on the process and then I'm starting reading in separate thread from STDOUT pipe.
Before thread is initiated I resume suspended process.
In result I'm getting nothing from ReadFile call, it just stops and waits for data to arrive even when the process is finished.
Here is the code
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#define BUFSIZE 4096
HANDLE g_hChildStd_IN_Rd = NULL;
HANDLE g_hChildStd_IN_Wr = NULL;
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_RdDup = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
HANDLE g_hSavedStd_OUT_Wr = NULL;
HANDLE g_hInputFile = NULL;
DWORD WINAPI CreateChildProcess(LPVOID param);
void WriteToPipe(void);
DWORD WINAPI ReadFromPipe(LPVOID param);
void ErrorExit(PTSTR);
PROCESS_INFORMATION piProcInfo;
int _tmain(int argc, TCHAR *argv[])
{
SECURITY_ATTRIBUTES saAttr;
printf("\n->Start of parent execution.\n");
// Set the bInheritHandle flag so pipe handles are inherited.
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Create a pipe for the child process's STDOUT.
if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) )
ErrorExit(TEXT("StdoutRd CreatePipe"));
// Ensure the read handle to the pipe for STDOUT is not inherited.
if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) )
ErrorExit(TEXT("Stdout SetHandleInformation"));
// Create a pipe for the child process's STDIN.
if (! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0))
ErrorExit(TEXT("Stdin CreatePipe"));
// Ensure the write handle to the pipe for STDIN is not inherited.
if ( ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
ErrorExit(TEXT("Stdin SetHandleInformation"));
STARTUPINFO siStartInfo;
ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = g_hChildStd_OUT_Wr;
siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
siStartInfo.hStdInput = g_hChildStd_IN_Rd;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
//CreateThread(&saAttr,0, CreateChildProcess, &siStartInfo, 0, NULL);
CreateChildProcess(&siStartInfo);
ResumeThread(piProcInfo.hThread);
printf( "\n->Contents of child process STDOUT:\n\n", argv[1]);
//ReadFromPipe(NULL);
HANDLE thread = CreateThread(&saAttr,0, ReadFromPipe, &siStartInfo, 0, NULL);
WaitForSingleObject(thread, INFINITE);
printf("\n->End of parent execution.\n");
// The remaining open handles are cleaned up when this process terminates.
// To avoid resource leaks in a larger application, close handles explicitly.
return 0;
}
DWORD WINAPI CreateChildProcess(LPVOID param)
// Create a child process that uses the previously created pipes for STDIN and STDOUT.
{
TCHAR szCmdline[]=TEXT("C:\\GnuWin32\\bin\\ls.exe");
STARTUPINFO *siStartInfo = (STARTUPINFO*)param;
BOOL bSuccess = FALSE;
// Set up members of the PROCESS_INFORMATION structure.
ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
// Set up members of the STARTUPINFO structure.
// This structure specifies the STDIN and STDOUT handles for redirection.
// Create the child process.
bSuccess = CreateProcess(NULL,
szCmdline, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
CREATE_SUSPENDED | CREATE_SEPARATE_WOW_VDM | CREATE_NO_WINDOW, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
//If resumethread is here - it works well
// If an error occurs, exit the application.
if ( ! bSuccess )
ErrorExit(TEXT("CreateProcess"));
else
{
// Close handles to the child process and its primary thread.
// Some applications might keep these handles to monitor the status
// of the child process, for example.
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
}
return 0;
}
void WriteToPipe(void)
// Read from a file and write its contents to the pipe for the child's STDIN.
// Stop when there is no more data.
{
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
for (;;)
{
bSuccess = ReadFile(g_hInputFile, chBuf, BUFSIZE, &dwRead, NULL);
if ( ! bSuccess || dwRead == 0 ) break;
bSuccess = WriteFile(g_hChildStd_IN_Wr, chBuf, dwRead, &dwWritten, NULL);
if ( ! bSuccess ) break;
}
// Close the pipe handle so the child process stops reading.
if ( ! CloseHandle(g_hChildStd_IN_Wr) )
ErrorExit(TEXT("StdInWr CloseHandle"));
}
DWORD WINAPI ReadFromPipe(LPVOID param)
// Read output from the child process's pipe for STDOUT
// and write to the parent process's pipe for STDOUT.
// Stop when there is no more data.
{
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
for (;;)
{
bSuccess = ReadFile( g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL);
if( ! bSuccess || dwRead == 0 ) break;
bSuccess = WriteFile(hParentStdOut, chBuf,
dwRead, &dwWritten, NULL);
if (! bSuccess ) break;
}
return 0;
}
void ErrorExit(PTSTR lpszFunction)
// Format a readable error message, display a message box,
// and exit from the application.
{
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)*sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(1);
}
And if I call ResumeThread(piProcInfo.hThread); just after CreateProcess function - It works well. But I need to keep creation in separate function anyway and call ResumeThread few functions after.
So, I would like to what to do to make program get suspended process's output in separate thread.
Always check return values.
You're trying to call ResumeThread on a handle that's already been closed. If you had checked the return value, you'd have noticed that this function wasn't succeeding, which would have told you what the problem was.
Remove CloseHandle(piProcInfo.hThread) from CreateChildProcess and the call to ResumeThread will work.
You should probably also be closing g_hChildStd_OUT_Wr and g_hChildStd_IN_Rd after creating the child process, so that you can tell when the child process exits.