forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
processutils.cpp
473 lines (393 loc) · 14.2 KB
/
processutils.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//===========================================================================//
#if !defined( _X360 )
#include <windows.h>
#endif
#include "vstdlib/iprocessutils.h"
#include "tier1/utllinkedlist.h"
#include "tier1/utlstring.h"
#include "tier1/utlbuffer.h"
#include "tier1/tier1.h"
//-----------------------------------------------------------------------------
// At the moment, we can only run one process at a time
//-----------------------------------------------------------------------------
class CProcessUtils : public CTier1AppSystem< IProcessUtils >
{
typedef CTier1AppSystem< IProcessUtils > BaseClass;
public:
CProcessUtils() : BaseClass( false ) {}
// Inherited from IAppSystem
virtual InitReturnVal_t Init();
virtual void Shutdown();
// Inherited from IProcessUtils
virtual ProcessHandle_t StartProcess( const char *pCommandLine, bool bConnectStdPipes );
virtual ProcessHandle_t StartProcess( int argc, const char **argv, bool bConnectStdPipes );
virtual void CloseProcess( ProcessHandle_t hProcess );
virtual void AbortProcess( ProcessHandle_t hProcess );
virtual bool IsProcessComplete( ProcessHandle_t hProcess );
virtual void WaitUntilProcessCompletes( ProcessHandle_t hProcess );
virtual int SendProcessInput( ProcessHandle_t hProcess, char *pBuf, int nBufLen );
virtual int GetProcessOutputSize( ProcessHandle_t hProcess );
virtual int GetProcessOutput( ProcessHandle_t hProcess, char *pBuf, int nBufLen );
virtual int GetProcessExitCode( ProcessHandle_t hProcess );
private:
struct ProcessInfo_t
{
HANDLE m_hChildStdinRd;
HANDLE m_hChildStdinWr;
HANDLE m_hChildStdoutRd;
HANDLE m_hChildStdoutWr;
HANDLE m_hChildStderrWr;
HANDLE m_hProcess;
CUtlString m_CommandLine;
CUtlBuffer m_ProcessOutput;
};
// Returns the last error that occurred
char *GetErrorString( char *pBuf, int nBufLen );
// creates the process, adds it to the list and writes the windows HANDLE into info.m_hProcess
ProcessHandle_t CreateProcess( ProcessInfo_t &info, bool bConnectStdPipes );
// Shuts down the process handle
void ShutdownProcess( ProcessHandle_t hProcess );
// Methods used to read output back from a process
int GetActualProcessOutputSize( ProcessHandle_t hProcess );
int GetActualProcessOutput( ProcessHandle_t hProcess, char *pBuf, int nBufLen );
CUtlFixedLinkedList< ProcessInfo_t > m_Processes;
ProcessHandle_t m_hCurrentProcess;
bool m_bInitialized;
};
//-----------------------------------------------------------------------------
// Purpose: singleton accessor
//-----------------------------------------------------------------------------
static CProcessUtils s_ProcessUtils;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CProcessUtils, IProcessUtils, PROCESS_UTILS_INTERFACE_VERSION, s_ProcessUtils );
//-----------------------------------------------------------------------------
// Initialize, shutdown process system
//-----------------------------------------------------------------------------
InitReturnVal_t CProcessUtils::Init()
{
InitReturnVal_t nRetVal = BaseClass::Init();
if ( nRetVal != INIT_OK )
return nRetVal;
m_bInitialized = true;
m_hCurrentProcess = PROCESS_HANDLE_INVALID;
return INIT_OK;
}
void CProcessUtils::Shutdown()
{
Assert( m_bInitialized );
Assert( m_Processes.Count() == 0 );
if ( m_Processes.Count() != 0 )
{
AbortProcess( m_hCurrentProcess );
}
m_bInitialized = false;
return BaseClass::Shutdown();
}
//-----------------------------------------------------------------------------
// Returns the last error that occurred
//-----------------------------------------------------------------------------
char *CProcessUtils::GetErrorString( char *pBuf, int nBufLen )
{
FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, pBuf, nBufLen, NULL );
char *p = strchr(pBuf, '\r'); // get rid of \r\n
if(p)
{
p[0] = 0;
}
return pBuf;
}
ProcessHandle_t CProcessUtils::CreateProcess( ProcessInfo_t &info, bool bConnectStdPipes )
{
STARTUPINFO si;
memset(&si, 0, sizeof si);
si.cb = sizeof(si);
if ( bConnectStdPipes )
{
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = info.m_hChildStdinRd;
si.hStdError = info.m_hChildStderrWr;
si.hStdOutput = info.m_hChildStdoutWr;
}
PROCESS_INFORMATION pi;
if ( ::CreateProcess( NULL, info.m_CommandLine.GetForModify(), NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &si, &pi ) )
{
info.m_hProcess = pi.hProcess;
m_hCurrentProcess = m_Processes.AddToTail( info );
return m_hCurrentProcess;
}
char buf[ 512 ];
Warning( "Could not execute the command:\n %s\n"
"Windows gave the error message:\n \"%s\"\n",
info.m_CommandLine.Get(), GetErrorString( buf, sizeof(buf) ) );
return PROCESS_HANDLE_INVALID;
}
//-----------------------------------------------------------------------------
// Options for compilation
//-----------------------------------------------------------------------------
ProcessHandle_t CProcessUtils::StartProcess( const char *pCommandLine, bool bConnectStdPipes )
{
Assert( m_bInitialized );
// NOTE: For the moment, we can only run one process at a time
// although in the future, I expect to have a process queue.
if ( m_hCurrentProcess != PROCESS_HANDLE_INVALID )
{
WaitUntilProcessCompletes( m_hCurrentProcess );
}
ProcessInfo_t info;
info.m_CommandLine = pCommandLine;
if ( !bConnectStdPipes )
{
info.m_hChildStderrWr = INVALID_HANDLE_VALUE;
info.m_hChildStdinRd = info.m_hChildStdinWr = INVALID_HANDLE_VALUE;
info.m_hChildStdoutRd = info.m_hChildStdoutWr = INVALID_HANDLE_VALUE;
return CreateProcess( info, false );
}
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's STDOUT.
if ( CreatePipe( &info.m_hChildStdoutRd, &info.m_hChildStdoutWr, &saAttr, 0 ) )
{
if ( CreatePipe( &info.m_hChildStdinRd, &info.m_hChildStdinWr, &saAttr, 0 ) )
{
if ( DuplicateHandle( GetCurrentProcess(), info.m_hChildStdoutWr, GetCurrentProcess(),
&info.m_hChildStderrWr, 0, TRUE, DUPLICATE_SAME_ACCESS ) )
{
// _setmode( info.m_hChildStdoutRd, _O_TEXT );
// _setmode( info.m_hChildStdoutWr, _O_TEXT );
// _setmode( info.m_hChildStderrWr, _O_TEXT );
ProcessHandle_t hProcess = CreateProcess( info, true );
if ( hProcess != PROCESS_HANDLE_INVALID )
return hProcess;
CloseHandle( info.m_hChildStderrWr );
}
CloseHandle( info.m_hChildStdinRd );
CloseHandle( info.m_hChildStdinWr );
}
CloseHandle( info.m_hChildStdoutRd );
CloseHandle( info.m_hChildStdoutWr );
}
return PROCESS_HANDLE_INVALID;
}
//-----------------------------------------------------------------------------
// Start up a process
//-----------------------------------------------------------------------------
ProcessHandle_t CProcessUtils::StartProcess( int argc, const char **argv, bool bConnectStdPipes )
{
CUtlString commandLine;
for ( int i = 0; i < argc; ++i )
{
commandLine += argv[i];
if ( i != argc-1 )
{
commandLine += " ";
}
}
return StartProcess( commandLine.Get(), bConnectStdPipes );
}
//-----------------------------------------------------------------------------
// Shuts down the process handle
//-----------------------------------------------------------------------------
void CProcessUtils::ShutdownProcess( ProcessHandle_t hProcess )
{
ProcessInfo_t& info = m_Processes[hProcess];
CloseHandle( info.m_hChildStderrWr );
CloseHandle( info.m_hChildStdinRd );
CloseHandle( info.m_hChildStdinWr );
CloseHandle( info.m_hChildStdoutRd );
CloseHandle( info.m_hChildStdoutWr );
m_Processes.Remove( hProcess );
}
//-----------------------------------------------------------------------------
// Closes the process
//-----------------------------------------------------------------------------
void CProcessUtils::CloseProcess( ProcessHandle_t hProcess )
{
Assert( m_bInitialized );
if ( hProcess != PROCESS_HANDLE_INVALID )
{
WaitUntilProcessCompletes( hProcess );
ShutdownProcess( hProcess );
}
}
//-----------------------------------------------------------------------------
// Aborts the process
//-----------------------------------------------------------------------------
void CProcessUtils::AbortProcess( ProcessHandle_t hProcess )
{
Assert( m_bInitialized );
if ( hProcess != PROCESS_HANDLE_INVALID )
{
if ( !IsProcessComplete( hProcess ) )
{
ProcessInfo_t& info = m_Processes[hProcess];
TerminateProcess( info.m_hProcess, 1 );
}
ShutdownProcess( hProcess );
}
}
//-----------------------------------------------------------------------------
// Returns true if the process is complete
//-----------------------------------------------------------------------------
bool CProcessUtils::IsProcessComplete( ProcessHandle_t hProcess )
{
Assert( m_bInitialized );
Assert( hProcess != PROCESS_HANDLE_INVALID );
if ( m_hCurrentProcess != hProcess )
return true;
HANDLE h = m_Processes[hProcess].m_hProcess;
return ( WaitForSingleObject( h, 0 ) != WAIT_TIMEOUT );
}
//-----------------------------------------------------------------------------
// Methods used to write input into a process
//-----------------------------------------------------------------------------
int CProcessUtils::SendProcessInput( ProcessHandle_t hProcess, char *pBuf, int nBufLen )
{
// Unimplemented yet
Assert( 0 );
return 0;
}
//-----------------------------------------------------------------------------
// Methods used to read output back from a process
//-----------------------------------------------------------------------------
int CProcessUtils::GetActualProcessOutputSize( ProcessHandle_t hProcess )
{
Assert( hProcess != PROCESS_HANDLE_INVALID );
ProcessInfo_t& info = m_Processes[ hProcess ];
if ( info.m_hChildStdoutRd == INVALID_HANDLE_VALUE )
return 0;
DWORD dwCount = 0;
if ( !PeekNamedPipe( info.m_hChildStdoutRd, NULL, NULL, NULL, &dwCount, NULL ) )
{
char buf[ 512 ];
Warning( "Could not read from pipe associated with command %s\n"
"Windows gave the error message:\n \"%s\"\n",
info.m_CommandLine.Get(), GetErrorString( buf, sizeof(buf) ) );
return 0;
}
// Add 1 for auto-NULL termination
return ( dwCount > 0 ) ? (int)dwCount + 1 : 0;
}
int CProcessUtils::GetActualProcessOutput( ProcessHandle_t hProcess, char *pBuf, int nBufLen )
{
ProcessInfo_t& info = m_Processes[ hProcess ];
if ( info.m_hChildStdoutRd == INVALID_HANDLE_VALUE )
return 0;
DWORD dwCount = 0;
DWORD dwRead = 0;
// FIXME: Is there a way of making pipes be text mode so we don't get /n/rs back?
char *pTempBuf = (char*)_alloca( nBufLen );
if ( !PeekNamedPipe( info.m_hChildStdoutRd, NULL, NULL, NULL, &dwCount, NULL ) )
{
char buf[ 512 ];
Warning( "Could not read from pipe associated with command %s\n"
"Windows gave the error message:\n \"%s\"\n",
info.m_CommandLine.Get(), GetErrorString( buf, sizeof(buf) ) );
return 0;
}
dwCount = min( dwCount, (DWORD)nBufLen - 1 );
ReadFile( info.m_hChildStdoutRd, pTempBuf, dwCount, &dwRead, NULL);
// Convert /n/r -> /n
int nActualCountRead = 0;
for ( unsigned int i = 0; i < dwRead; ++i )
{
char c = pTempBuf[i];
if ( c == '\r' )
{
if ( ( i+1 < dwRead ) && ( pTempBuf[i+1] == '\n' ) )
{
pBuf[nActualCountRead++] = '\n';
++i;
continue;
}
}
pBuf[nActualCountRead++] = c;
}
return nActualCountRead;
}
int CProcessUtils::GetProcessOutputSize( ProcessHandle_t hProcess )
{
Assert( m_bInitialized );
if ( hProcess == PROCESS_HANDLE_INVALID )
return 0;
return GetActualProcessOutputSize( hProcess ) + m_Processes[hProcess].m_ProcessOutput.TellPut();
}
int CProcessUtils::GetProcessOutput( ProcessHandle_t hProcess, char *pBuf, int nBufLen )
{
Assert( m_bInitialized );
if ( hProcess == PROCESS_HANDLE_INVALID )
return 0;
ProcessInfo_t &info = m_Processes[hProcess];
int nCachedBytes = info.m_ProcessOutput.TellPut();
int nBytesRead = 0;
if ( nCachedBytes )
{
nBytesRead = min( nBufLen-1, nCachedBytes );
info.m_ProcessOutput.Get( pBuf, nBytesRead );
pBuf[ nBytesRead ] = 0;
nBufLen -= nBytesRead;
pBuf += nBytesRead;
if ( info.m_ProcessOutput.GetBytesRemaining() == 0 )
{
info.m_ProcessOutput.Purge();
}
if ( nBufLen <= 1 )
return nBytesRead;
}
// Auto-NULL terminate
int nActualCountRead = GetActualProcessOutput( hProcess, pBuf, nBufLen );
pBuf[nActualCountRead] = 0;
return nActualCountRead + nBytesRead + 1;
}
//-----------------------------------------------------------------------------
// Returns the exit code for the process. Doesn't work unless the process is complete
//-----------------------------------------------------------------------------
int CProcessUtils::GetProcessExitCode( ProcessHandle_t hProcess )
{
Assert( m_bInitialized );
ProcessInfo_t &info = m_Processes[hProcess];
DWORD nExitCode;
BOOL bOk = GetExitCodeProcess( info.m_hProcess, &nExitCode );
if ( !bOk || nExitCode == STILL_ACTIVE )
return -1;
return nExitCode;
}
//-----------------------------------------------------------------------------
// Waits until a process is complete
//-----------------------------------------------------------------------------
void CProcessUtils::WaitUntilProcessCompletes( ProcessHandle_t hProcess )
{
Assert( m_bInitialized );
// For the moment, we can only run one process at a time
if ( ( hProcess == PROCESS_HANDLE_INVALID ) || ( m_hCurrentProcess != hProcess ) )
return;
ProcessInfo_t &info = m_Processes[ hProcess ];
if ( info.m_hChildStdoutRd == INVALID_HANDLE_VALUE )
{
WaitForSingleObject( info.m_hProcess, INFINITE );
}
else
{
// NOTE: The called process can block during writes to stderr + stdout
// if the pipe buffer is empty. Therefore, waiting INFINITE is not
// possible here. We must queue up messages received to allow the
// process to continue
while ( WaitForSingleObject( info.m_hProcess, 100 ) == WAIT_TIMEOUT )
{
int nLen = GetActualProcessOutputSize( hProcess );
if ( nLen > 0 )
{
int nPut = info.m_ProcessOutput.TellPut();
info.m_ProcessOutput.EnsureCapacity( nPut + nLen );
int nBytesRead = GetActualProcessOutput( hProcess, (char*)info.m_ProcessOutput.PeekPut(), nLen );
info.m_ProcessOutput.SeekPut( CUtlBuffer::SEEK_HEAD, nPut + nBytesRead );
}
}
}
m_hCurrentProcess = PROCESS_HANDLE_INVALID;
}