]> git.saurik.com Git - wxWidgets.git/blob - src/msw/utilsexc.cpp
8fcae76c3c5789222d8cab80b2d7614bd1735ec6
[wxWidgets.git] / src / msw / utilsexc.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: msw/utilsexec.cpp
3 // Purpose: Various utilities
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 04/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart and Markus Holzem
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 #pragma implementation
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 #ifndef WX_PRECOMP
32 #include "wx/utils.h"
33 #include "wx/app.h"
34 #include "wx/intl.h"
35 #endif
36
37 #include "wx/log.h"
38
39 #ifdef __WIN32__
40 #include "wx/stream.h"
41 #include "wx/process.h"
42 #endif
43
44 #include "wx/msw/private.h"
45
46 #include <ctype.h>
47
48 #if !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__SALFORDC__) && !defined(__WXMICROWIN__)
49 #include <direct.h>
50 #ifndef __MWERKS__
51 #include <dos.h>
52 #endif
53 #endif
54
55 #if defined(__GNUWIN32__) && !defined(__TWIN32__)
56 #include <sys/unistd.h>
57 #include <sys/stat.h>
58 #endif
59
60 #if defined(__WIN32__) && !defined(__WXWINE__) && !defined(__WXMICROWIN__)
61 #include <io.h>
62
63 #ifndef __GNUWIN32__
64 #include <shellapi.h>
65 #endif
66 #endif
67
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #ifndef __WATCOMC__
72 #if !(defined(_MSC_VER) && (_MSC_VER > 800))
73 #include <errno.h>
74 #endif
75 #endif
76 #include <stdarg.h>
77
78 #if wxUSE_IPC
79 #include "wx/dde.h" // for WX_DDE hack in wxExecute
80 #endif // wxUSE_IPC
81
82 // ----------------------------------------------------------------------------
83 // constants
84 // ----------------------------------------------------------------------------
85
86 // this message is sent when the process we're waiting for terminates
87 #define wxWM_PROC_TERMINATED (WM_USER + 10000)
88
89 // ----------------------------------------------------------------------------
90 // this module globals
91 // ----------------------------------------------------------------------------
92
93 // we need to create a hidden window to receive the process termination
94 // notifications and for this we need a (Win) class name for it which we will
95 // register the first time it's needed
96 static const wxChar *gs_classForHiddenWindow = NULL;
97
98 // ----------------------------------------------------------------------------
99 // private types
100 // ----------------------------------------------------------------------------
101
102 // structure describing the process we're being waiting for
103 struct wxExecuteData
104 {
105 public:
106 ~wxExecuteData()
107 {
108 #ifndef __WIN16__
109 if ( !::CloseHandle(hProcess) )
110 {
111 wxLogLastError(wxT("CloseHandle(hProcess)"));
112 }
113 #endif
114 }
115
116 HWND hWnd; // window to send wxWM_PROC_TERMINATED to
117 HANDLE hProcess; // handle of the process
118 DWORD dwProcessId; // pid of the process
119 wxProcess *handler;
120 DWORD dwExitCode; // the exit code of the process
121 bool state; // set to FALSE when the process finishes
122 };
123
124 #if defined(__WIN32__) && wxUSE_STREAMS
125
126 // ----------------------------------------------------------------------------
127 // wxPipeStreams
128 // ----------------------------------------------------------------------------
129
130 class wxPipeInputStream: public wxInputStream
131 {
132 public:
133 wxPipeInputStream(HANDLE hInput);
134 ~wxPipeInputStream();
135
136 virtual bool Eof() const;
137
138 protected:
139 size_t OnSysRead(void *buffer, size_t len);
140
141 protected:
142 HANDLE m_hInput;
143 };
144
145 class wxPipeOutputStream: public wxOutputStream
146 {
147 public:
148 wxPipeOutputStream(HANDLE hOutput);
149 ~wxPipeOutputStream();
150
151 protected:
152 size_t OnSysWrite(const void *buffer, size_t len);
153
154 protected:
155 HANDLE m_hOutput;
156 };
157
158 // ==================
159 // wxPipeInputStream
160 // ==================
161
162 wxPipeInputStream::wxPipeInputStream(HANDLE hInput)
163 {
164 m_hInput = hInput;
165 }
166
167 wxPipeInputStream::~wxPipeInputStream()
168 {
169 ::CloseHandle(m_hInput);
170 }
171
172 bool wxPipeInputStream::Eof() const
173 {
174 DWORD nAvailable;
175
176 // function name is misleading, it works with anon pipes as well
177 DWORD rc = ::PeekNamedPipe
178 (
179 m_hInput, // handle
180 NULL, 0, // ptr to buffer and its size
181 NULL, // [out] bytes read
182 &nAvailable, // [out] bytes available
183 NULL // [out] bytes left
184 );
185
186 if ( !rc )
187 {
188 if ( ::GetLastError() != ERROR_BROKEN_PIPE )
189 {
190 // unexpected error
191 wxLogLastError(_T("PeekNamedPipe"));
192 }
193
194 // don't try to continue reading from a pipe if an error occured or if
195 // it had been closed
196 return TRUE;
197 }
198 else
199 {
200 return nAvailable == 0;
201 }
202 }
203
204 size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len)
205 {
206 // reading from a pipe may block if there is no more data, always check for
207 // EOF first
208 m_lasterror = wxSTREAM_NOERROR;
209 if ( Eof() )
210 return 0;
211
212 DWORD bytesRead;
213 if ( !::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) )
214 {
215 if ( ::GetLastError() == ERROR_BROKEN_PIPE )
216 m_lasterror = wxSTREAM_EOF;
217 else
218 m_lasterror = wxSTREAM_READ_ERROR;
219 }
220
221 return bytesRead;
222 }
223
224 // ==================
225 // wxPipeOutputStream
226 // ==================
227
228 wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput)
229 {
230 m_hOutput = hOutput;
231 }
232
233 wxPipeOutputStream::~wxPipeOutputStream()
234 {
235 ::CloseHandle(m_hOutput);
236 }
237
238 size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len)
239 {
240 DWORD bytesRead;
241
242 m_lasterror = wxSTREAM_NOERROR;
243 if ( !::WriteFile(m_hOutput, buffer, len, &bytesRead, NULL) )
244 {
245 if ( ::GetLastError() == ERROR_BROKEN_PIPE )
246 m_lasterror = wxSTREAM_EOF;
247 else
248 m_lasterror = wxSTREAM_READ_ERROR;
249 }
250
251 return bytesRead;
252 }
253
254 #endif // __WIN32__
255
256 // ============================================================================
257 // implementation
258 // ============================================================================
259
260 #ifdef __WIN32__
261
262 static DWORD __stdcall wxExecuteThread(void *arg)
263 {
264 wxExecuteData *data = (wxExecuteData*)arg;
265
266 WaitForSingleObject(data->hProcess, INFINITE);
267
268 // get the exit code
269 if ( !GetExitCodeProcess(data->hProcess, &data->dwExitCode) )
270 {
271 wxLogLastError(wxT("GetExitCodeProcess"));
272 }
273
274 wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE,
275 wxT("process should have terminated") );
276
277 // send a message indicating process termination to the window
278 SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data);
279
280 return 0;
281 }
282
283 // window procedure of a hidden window which is created just to receive
284 // the notification message when a process exits
285 LRESULT APIENTRY _EXPORT wxExecuteWindowCbk(HWND hWnd, UINT message,
286 WPARAM wParam, LPARAM lParam)
287 {
288 if ( message == wxWM_PROC_TERMINATED )
289 {
290 DestroyWindow(hWnd); // we don't need it any more
291
292 wxExecuteData *data = (wxExecuteData *)lParam;
293 if ( data->handler )
294 {
295 data->handler->OnTerminate((int)data->dwProcessId,
296 (int)data->dwExitCode);
297 }
298
299 if ( data->state )
300 {
301 // we're executing synchronously, tell the waiting thread
302 // that the process finished
303 data->state = 0;
304 }
305 else
306 {
307 // asynchronous execution - we should do the clean up
308 delete data;
309 }
310
311 return 0;
312 }
313 else
314 {
315 return DefWindowProc(hWnd, message, wParam, lParam);
316 }
317 }
318 #endif // Win32
319
320 #if wxUSE_IPC
321
322 // connect to the given server via DDE and ask it to execute the command
323 static bool wxExecuteDDE(const wxString& ddeServer,
324 const wxString& ddeTopic,
325 const wxString& ddeCommand)
326 {
327 bool ok;
328
329 wxDDEClient client;
330 wxConnectionBase *conn = client.MakeConnection(_T(""),
331 ddeServer,
332 ddeTopic);
333 if ( !conn )
334 {
335 ok = FALSE;
336 }
337 else // connected to DDE server
338 {
339 // the added complication here is that although most
340 // programs use XTYP_EXECUTE for their DDE API, some
341 // important ones - like IE and other MS stuff - use
342 // XTYP_REQUEST!
343 //
344 // so we try it first and then the other one if it
345 // failed
346 {
347 wxLogNull noErrors;
348 ok = conn->Request(ddeCommand) != NULL;
349 }
350
351 if ( !ok )
352 {
353 // now try execute - but show the errors
354 ok = conn->Execute(ddeCommand);
355 }
356 }
357
358 return ok;
359 }
360
361 #endif // wxUSE_IPC
362
363 long wxExecute(const wxString& cmd, bool sync, wxProcess *handler)
364 {
365 wxCHECK_MSG( !!cmd, 0, wxT("empty command in wxExecute") );
366
367 wxString command;
368
369 #if wxUSE_IPC
370 // DDE hack: this is really not pretty, but we need to allow this for
371 // transparent handling of DDE servers in wxMimeTypesManager. Usually it
372 // returns the command which should be run to view/open/... a file of the
373 // given type. Sometimes, however, this command just launches the server
374 // and an additional DDE request must be made to really open the file. To
375 // keep all this well hidden from the application, we allow a special form
376 // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which
377 // case we execute just <command> and process the rest below
378 wxString ddeServer, ddeTopic, ddeCommand;
379 static const size_t lenDdePrefix = 7; // strlen("WX_DDE:")
380 if ( cmd.Left(lenDdePrefix) == _T("WX_DDE#") )
381 {
382 // speed up the concatenations below
383 ddeServer.reserve(256);
384 ddeTopic.reserve(256);
385 ddeCommand.reserve(256);
386
387 const wxChar *p = cmd.c_str() + 7;
388 while ( *p && *p != _T('#') )
389 {
390 command += *p++;
391 }
392
393 if ( *p )
394 {
395 // skip '#'
396 p++;
397 }
398 else
399 {
400 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
401 }
402
403 while ( *p && *p != _T('#') )
404 {
405 ddeServer += *p++;
406 }
407
408 if ( *p )
409 {
410 // skip '#'
411 p++;
412 }
413 else
414 {
415 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
416 }
417
418 while ( *p && *p != _T('#') )
419 {
420 ddeTopic += *p++;
421 }
422
423 if ( *p )
424 {
425 // skip '#'
426 p++;
427 }
428 else
429 {
430 wxFAIL_MSG(_T("invalid WX_DDE command in wxExecute"));
431 }
432
433 while ( *p )
434 {
435 ddeCommand += *p++;
436 }
437
438 // if we want to just launch the program and not wait for its
439 // termination, try to execute DDE command right now, it can succeed if
440 // the process is already running - but as it fails if it's not
441 // running, suppress any errors it might generate
442 if ( !sync )
443 {
444 wxLogNull noErrors;
445 if ( wxExecuteDDE(ddeServer, ddeTopic, ddeCommand) )
446 {
447 // a dummy PID - this is a hack, of course, but it's well worth
448 // it as we don't open a new server each time we're called
449 // which would be quite bad
450 return -1;
451 }
452 }
453 }
454 else
455 #endif // wxUSE_IPC
456 {
457 // no DDE
458 command = cmd;
459 }
460
461 #if defined(__WIN32__) && !defined(__TWIN32__)
462
463 // the IO redirection is only supported with wxUSE_STREAMS
464 BOOL redirect = FALSE;
465 #if wxUSE_STREAMS
466 // the first elements are reading ends, the second are the writing ones
467 HANDLE hpipeStdin[2],
468 hpipeStdout[2],
469 hpipeStderr[2];
470 HANDLE hpipeStdinWrite = INVALID_HANDLE_VALUE;
471
472 // open the pipes to which child process IO will be redirected if needed
473 if ( handler && handler->IsRedirected() )
474 {
475 // default secutiry attributes
476 SECURITY_ATTRIBUTES security;
477
478 security.nLength = sizeof(security);
479 security.lpSecurityDescriptor = NULL;
480 security.bInheritHandle = TRUE;
481
482 // create stdin pipe
483 if ( !::CreatePipe(&hpipeStdin[0], &hpipeStdin[1], &security, 0) )
484 {
485 wxLogSysError(_("Can't create the inter-process read pipe"));
486
487 // indicate failure in both cases
488 return sync ? -1 : 0;
489 }
490
491 // and a stdout one
492 if ( !::CreatePipe(&hpipeStdout[0], &hpipeStdout[1], &security, 0) )
493 {
494 ::CloseHandle(hpipeStdin[0]);
495 ::CloseHandle(hpipeStdin[1]);
496
497 wxLogSysError(_("Can't create the inter-process write pipe"));
498
499 return sync ? -1 : 0;
500 }
501
502 (void)::CreatePipe(&hpipeStderr[0], &hpipeStderr[1], &security, 0);
503
504 redirect = TRUE;
505 }
506 #endif // wxUSE_STREAMS
507
508 // create the process
509 STARTUPINFO si;
510 wxZeroMemory(si);
511 si.cb = sizeof(si);
512
513 #if wxUSE_STREAMS
514 if ( redirect )
515 {
516 // when the std IO is redirected, we don't show the (console) process
517 // window
518 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
519
520 si.hStdInput = hpipeStdin[0];
521 si.hStdOutput = hpipeStdout[1];
522 si.hStdError = hpipeStderr[1];
523
524 si.wShowWindow = SW_HIDE;
525
526 // we must duplicate the handle to the write side of stdin pipe to make
527 // it non inheritable: indeed, we must close hpipeStdin[1] before
528 // launching the child process as otherwise this handle will be
529 // inherited by the child which will never close it and so the pipe
530 // will never be closed and the child will be left stuck in ReadFile()
531 if ( !::DuplicateHandle
532 (
533 GetCurrentProcess(),
534 hpipeStdin[1],
535 GetCurrentProcess(),
536 &hpipeStdinWrite,
537 0, // desired access: unused here
538 FALSE, // not inherited
539 DUPLICATE_SAME_ACCESS // same access as for src handle
540 ) )
541 {
542 wxLogLastError(_T("DuplicateHandle"));
543 }
544
545 ::CloseHandle(hpipeStdin[1]);
546 }
547 #endif // wxUSE_STREAMS
548
549 PROCESS_INFORMATION pi;
550 DWORD dwFlags = CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED;
551
552 bool ok = ::CreateProcess
553 (
554 NULL, // application name (use only cmd line)
555 (wxChar *)
556 command.c_str(), // full command line
557 NULL, // security attributes: defaults for both
558 NULL, // the process and its main thread
559 redirect, // inherit handles if we use pipes
560 dwFlags, // process creation flags
561 NULL, // environment (use the same)
562 NULL, // current directory (use the same)
563 &si, // startup info (unused here)
564 &pi // process info
565 ) != 0;
566
567 #if wxUSE_STREAMS
568 // we can close the pipe ends used by child anyhow
569 if ( redirect )
570 {
571 ::CloseHandle(hpipeStdin[0]);
572 ::CloseHandle(hpipeStdout[1]);
573 ::CloseHandle(hpipeStderr[1]);
574 }
575 #endif // wxUSE_STREAMS
576
577 if ( !ok )
578 {
579 #if wxUSE_STREAMS
580 // close the other handles too
581 if ( redirect )
582 {
583 ::CloseHandle(hpipeStdout[0]);
584 ::CloseHandle(hpipeStderr[0]);
585 }
586 #endif // wxUSE_STREAMS
587
588 wxLogSysError(_("Execution of command '%s' failed"), command.c_str());
589
590 return sync ? -1 : 0;
591 }
592
593 #if wxUSE_STREAMS
594 if ( redirect )
595 {
596 // We can now initialize the wxStreams
597 wxInputStream *inStream = new wxPipeInputStream(hpipeStdout[0]),
598 *errStream = new wxPipeInputStream(hpipeStderr[0]);
599 wxOutputStream *outStream = new wxPipeOutputStream(hpipeStdinWrite);
600
601 handler->SetPipeStreams(inStream, outStream, errStream);
602 }
603 #endif // wxUSE_STREAMS
604
605 // register the class for the hidden window used for the notifications
606 if ( !gs_classForHiddenWindow )
607 {
608 gs_classForHiddenWindow = _T("wxHiddenWindow");
609
610 WNDCLASS wndclass;
611 wxZeroMemory(wndclass);
612 wndclass.lpfnWndProc = (WNDPROC)wxExecuteWindowCbk;
613 wndclass.hInstance = wxGetInstance();
614 wndclass.lpszClassName = gs_classForHiddenWindow;
615
616 if ( !::RegisterClass(&wndclass) )
617 {
618 wxLogLastError(wxT("RegisterClass(hidden window)"));
619 }
620 }
621
622 // create a hidden window to receive notification about process
623 // termination
624 HWND hwnd = ::CreateWindow(gs_classForHiddenWindow, NULL,
625 WS_OVERLAPPEDWINDOW,
626 0, 0, 0, 0, NULL,
627 (HMENU)NULL, wxGetInstance(), 0);
628 wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") );
629
630 // Alloc data
631 wxExecuteData *data = new wxExecuteData;
632 data->hProcess = pi.hProcess;
633 data->dwProcessId = pi.dwProcessId;
634 data->hWnd = hwnd;
635 data->state = sync;
636 if ( sync )
637 {
638 // handler may be !NULL for capturing program output, but we don't use
639 // it wxExecuteData struct in this case
640 data->handler = NULL;
641 }
642 else
643 {
644 // may be NULL or not
645 data->handler = handler;
646 }
647
648 DWORD tid;
649 HANDLE hThread = ::CreateThread(NULL,
650 0,
651 wxExecuteThread,
652 (void *)data,
653 0,
654 &tid);
655
656 // resume process we created now - whether the thread creation succeeded or
657 // not
658 if ( ::ResumeThread(pi.hThread) == (DWORD)-1 )
659 {
660 // ignore it - what can we do?
661 wxLogLastError(wxT("ResumeThread in wxExecute"));
662 }
663
664 // close unneeded handle
665 if ( !::CloseHandle(pi.hThread) )
666 wxLogLastError(wxT("CloseHandle(hThread)"));
667
668 if ( !hThread )
669 {
670 wxLogLastError(wxT("CreateThread in wxExecute"));
671
672 DestroyWindow(hwnd);
673 delete data;
674
675 // the process still started up successfully...
676 return pi.dwProcessId;
677 }
678
679 ::CloseHandle(hThread);
680
681 #if wxUSE_IPC
682 // second part of DDE hack: now establish the DDE conversation with the
683 // just launched process
684 if ( !ddeServer.empty() )
685 {
686 bool ok;
687
688 // give the process the time to init itself
689 //
690 // we use a very big timeout hoping that WaitForInputIdle() will return
691 // much sooner, but not INFINITE just in case the process hangs
692 // completely - like this we will regain control sooner or later
693 switch ( ::WaitForInputIdle(pi.hProcess, 10000 /* 10 seconds */) )
694 {
695 default:
696 wxFAIL_MSG( _T("unexpected WaitForInputIdle() return code") );
697 // fall through
698
699 case -1:
700 wxLogLastError(_T("WaitForInputIdle() in wxExecute"));
701
702 case WAIT_TIMEOUT:
703 wxLogDebug(_T("Timeout too small in WaitForInputIdle"));
704
705 ok = FALSE;
706 break;
707
708 case 0:
709 // ok, process ready to accept DDE requests
710 ok = wxExecuteDDE(ddeServer, ddeTopic, ddeCommand);
711 }
712 }
713 #endif // wxUSE_IPC
714
715 if ( !sync )
716 {
717 // clean up will be done when the process terminates
718
719 // return the pid
720 return pi.dwProcessId;
721 }
722
723 // waiting until command executed (disable everything while doing it)
724 #if wxUSE_GUI
725 {
726 wxBusyCursor bc;
727
728 wxWindowDisabler wd;
729 #endif // wxUSE_GUI
730
731 while ( data->state )
732 wxYield();
733
734 #if wxUSE_GUI
735 }
736 #endif // wxUSE_GUI
737
738 DWORD dwExitCode = data->dwExitCode;
739 delete data;
740
741 // return the exit code
742 return dwExitCode;
743 #else // Win16
744 long instanceID = WinExec((LPCSTR) WXSTRINGCAST command, SW_SHOW);
745 if (instanceID < 32) return(0);
746
747 if (sync) {
748 int running;
749 do {
750 wxYield();
751 running = GetModuleUsage((HINSTANCE)instanceID);
752 } while (running);
753 }
754
755 return(instanceID);
756 #endif // Win16/32
757 }
758
759 long wxExecute(char **argv, bool sync, wxProcess *handler)
760 {
761 wxString command;
762
763 while ( *argv != NULL )
764 {
765 command << *argv++ << ' ';
766 }
767
768 command.RemoveLast();
769
770 return wxExecute(command, sync, handler);
771 }
772