]>
Commit | Line | Data |
---|---|---|
1 | ///////////////////////////////////////////////////////////////////////////// | |
2 | // Name: src/msw/utilsexc.cpp | |
3 | // Purpose: wxExecute implementation for MSW | |
4 | // Author: Julian Smart | |
5 | // Modified by: | |
6 | // Created: 04/01/98 | |
7 | // RCS-ID: $Id$ | |
8 | // Copyright: (c) 1998-2002 wxWidgets dev team | |
9 | // Licence: wxWindows licence | |
10 | ///////////////////////////////////////////////////////////////////////////// | |
11 | ||
12 | // ============================================================================ | |
13 | // declarations | |
14 | // ============================================================================ | |
15 | ||
16 | // ---------------------------------------------------------------------------- | |
17 | // headers | |
18 | // ---------------------------------------------------------------------------- | |
19 | ||
20 | // For compilers that support precompilation, includes "wx.h". | |
21 | #include "wx/wxprec.h" | |
22 | ||
23 | #ifdef __BORLANDC__ | |
24 | #pragma hdrstop | |
25 | #endif | |
26 | ||
27 | #ifndef WX_PRECOMP | |
28 | #include "wx/utils.h" | |
29 | #include "wx/app.h" | |
30 | #include "wx/intl.h" | |
31 | #include "wx/log.h" | |
32 | #if wxUSE_STREAMS | |
33 | #include "wx/stream.h" | |
34 | #endif | |
35 | #include "wx/module.h" | |
36 | #endif | |
37 | ||
38 | #include "wx/process.h" | |
39 | #include "wx/thread.h" | |
40 | #include "wx/apptrait.h" | |
41 | #include "wx/evtloop.h" | |
42 | #include "wx/vector.h" | |
43 | ||
44 | ||
45 | #include "wx/msw/private.h" | |
46 | ||
47 | #include <ctype.h> | |
48 | ||
49 | #if !defined(__GNUWIN32__) && !defined(__WXMICROWIN__) && !defined(__WXWINCE__) | |
50 | #include <direct.h> | |
51 | #include <dos.h> | |
52 | #endif | |
53 | ||
54 | #if defined(__GNUWIN32__) | |
55 | #include <sys/unistd.h> | |
56 | #include <sys/stat.h> | |
57 | #endif | |
58 | ||
59 | #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__) | |
60 | #ifndef __UNIX__ | |
61 | #include <io.h> | |
62 | #endif | |
63 | ||
64 | #ifndef __GNUWIN32__ | |
65 | #include <shellapi.h> | |
66 | #endif | |
67 | #endif | |
68 | ||
69 | #include <stdio.h> | |
70 | #include <stdlib.h> | |
71 | #include <string.h> | |
72 | #ifndef __WATCOMC__ | |
73 | #if !(defined(_MSC_VER) && (_MSC_VER > 800)) | |
74 | #include <errno.h> | |
75 | #endif | |
76 | #endif | |
77 | #include <stdarg.h> | |
78 | ||
79 | #if wxUSE_IPC | |
80 | #include "wx/dde.h" // for WX_DDE hack in wxExecute | |
81 | #endif // wxUSE_IPC | |
82 | ||
83 | #include "wx/msw/private/hiddenwin.h" | |
84 | ||
85 | // FIXME-VC6: These are not defined in VC6 SDK headers. | |
86 | #ifndef BELOW_NORMAL_PRIORITY_CLASS | |
87 | #define BELOW_NORMAL_PRIORITY_CLASS 0x4000 | |
88 | #endif | |
89 | ||
90 | #ifndef ABOVE_NORMAL_PRIORITY_CLASS | |
91 | #define ABOVE_NORMAL_PRIORITY_CLASS 0x8000 | |
92 | #endif | |
93 | ||
94 | // ---------------------------------------------------------------------------- | |
95 | // constants | |
96 | // ---------------------------------------------------------------------------- | |
97 | ||
98 | // this message is sent when the process we're waiting for terminates | |
99 | #define wxWM_PROC_TERMINATED (WM_USER + 10000) | |
100 | ||
101 | // ---------------------------------------------------------------------------- | |
102 | // this module globals | |
103 | // ---------------------------------------------------------------------------- | |
104 | ||
105 | // we need to create a hidden window to receive the process termination | |
106 | // notifications and for this we need a (Win) class name for it which we will | |
107 | // register the first time it's needed | |
108 | static const wxChar *wxMSWEXEC_WNDCLASSNAME = wxT("_wxExecute_Internal_Class"); | |
109 | static const wxChar *gs_classForHiddenWindow = NULL; | |
110 | ||
111 | // event used to wake up threads waiting in wxExecuteThread | |
112 | static HANDLE gs_heventShutdown = NULL; | |
113 | ||
114 | // handles of all threads monitoring the execution of asynchronously running | |
115 | // processes | |
116 | static wxVector<HANDLE> gs_asyncThreads; | |
117 | ||
118 | // ---------------------------------------------------------------------------- | |
119 | // private types | |
120 | // ---------------------------------------------------------------------------- | |
121 | ||
122 | // structure describing the process we're being waiting for | |
123 | struct wxExecuteData | |
124 | { | |
125 | public: | |
126 | ~wxExecuteData() | |
127 | { | |
128 | if ( !::CloseHandle(hProcess) ) | |
129 | { | |
130 | wxLogLastError(wxT("CloseHandle(hProcess)")); | |
131 | } | |
132 | } | |
133 | ||
134 | HWND hWnd; // window to send wxWM_PROC_TERMINATED to | |
135 | HANDLE hProcess; // handle of the process | |
136 | DWORD dwProcessId; // pid of the process | |
137 | wxProcess *handler; | |
138 | DWORD dwExitCode; // the exit code of the process | |
139 | bool state; // set to false when the process finishes | |
140 | }; | |
141 | ||
142 | class wxExecuteModule : public wxModule | |
143 | { | |
144 | public: | |
145 | virtual bool OnInit() { return true; } | |
146 | virtual void OnExit() | |
147 | { | |
148 | if ( gs_heventShutdown ) | |
149 | { | |
150 | // stop any threads waiting for the termination of asynchronously | |
151 | // running processes | |
152 | if ( !::SetEvent(gs_heventShutdown) ) | |
153 | { | |
154 | wxLogDebug(wxT("Failed to set shutdown event in wxExecuteModule")); | |
155 | } | |
156 | ||
157 | ::CloseHandle(gs_heventShutdown); | |
158 | gs_heventShutdown = NULL; | |
159 | ||
160 | // now wait until they terminate | |
161 | if ( !gs_asyncThreads.empty() ) | |
162 | { | |
163 | const size_t numThreads = gs_asyncThreads.size(); | |
164 | ||
165 | if ( ::WaitForMultipleObjects | |
166 | ( | |
167 | numThreads, | |
168 | &gs_asyncThreads[0], | |
169 | TRUE, // wait for all of them to become signalled | |
170 | 3000 // long but finite value | |
171 | ) == WAIT_TIMEOUT ) | |
172 | { | |
173 | wxLogDebug(wxT("Failed to stop all wxExecute monitor threads")); | |
174 | } | |
175 | ||
176 | for ( size_t n = 0; n < numThreads; n++ ) | |
177 | { | |
178 | ::CloseHandle(gs_asyncThreads[n]); | |
179 | } | |
180 | ||
181 | gs_asyncThreads.clear(); | |
182 | } | |
183 | } | |
184 | ||
185 | if ( gs_classForHiddenWindow ) | |
186 | { | |
187 | if ( !::UnregisterClass(wxMSWEXEC_WNDCLASSNAME, wxGetInstance()) ) | |
188 | { | |
189 | wxLogLastError(wxT("UnregisterClass(wxExecClass)")); | |
190 | } | |
191 | ||
192 | gs_classForHiddenWindow = NULL; | |
193 | } | |
194 | } | |
195 | ||
196 | private: | |
197 | DECLARE_DYNAMIC_CLASS(wxExecuteModule) | |
198 | }; | |
199 | ||
200 | IMPLEMENT_DYNAMIC_CLASS(wxExecuteModule, wxModule) | |
201 | ||
202 | #if wxUSE_STREAMS && !defined(__WXWINCE__) | |
203 | ||
204 | // ---------------------------------------------------------------------------- | |
205 | // wxPipeStreams | |
206 | // ---------------------------------------------------------------------------- | |
207 | ||
208 | class wxPipeInputStream: public wxInputStream | |
209 | { | |
210 | public: | |
211 | wxPipeInputStream(HANDLE hInput); | |
212 | virtual ~wxPipeInputStream(); | |
213 | ||
214 | // returns true if the pipe is still opened | |
215 | bool IsOpened() const { return m_hInput != INVALID_HANDLE_VALUE; } | |
216 | ||
217 | // returns true if there is any data to be read from the pipe | |
218 | virtual bool CanRead() const; | |
219 | ||
220 | protected: | |
221 | size_t OnSysRead(void *buffer, size_t len); | |
222 | ||
223 | protected: | |
224 | HANDLE m_hInput; | |
225 | ||
226 | wxDECLARE_NO_COPY_CLASS(wxPipeInputStream); | |
227 | }; | |
228 | ||
229 | class wxPipeOutputStream: public wxOutputStream | |
230 | { | |
231 | public: | |
232 | wxPipeOutputStream(HANDLE hOutput); | |
233 | virtual ~wxPipeOutputStream() { Close(); } | |
234 | bool Close(); | |
235 | ||
236 | protected: | |
237 | size_t OnSysWrite(const void *buffer, size_t len); | |
238 | ||
239 | protected: | |
240 | HANDLE m_hOutput; | |
241 | ||
242 | wxDECLARE_NO_COPY_CLASS(wxPipeOutputStream); | |
243 | }; | |
244 | ||
245 | // define this to let wxexec.cpp know that we know what we're doing | |
246 | #define _WX_USED_BY_WXEXECUTE_ | |
247 | #include "../common/execcmn.cpp" | |
248 | ||
249 | // ---------------------------------------------------------------------------- | |
250 | // wxPipe represents a Win32 anonymous pipe | |
251 | // ---------------------------------------------------------------------------- | |
252 | ||
253 | class wxPipe | |
254 | { | |
255 | public: | |
256 | // the symbolic names for the pipe ends | |
257 | enum Direction | |
258 | { | |
259 | Read, | |
260 | Write | |
261 | }; | |
262 | ||
263 | // default ctor doesn't do anything | |
264 | wxPipe() { m_handles[Read] = m_handles[Write] = INVALID_HANDLE_VALUE; } | |
265 | ||
266 | // create the pipe, return true if ok, false on error | |
267 | bool Create() | |
268 | { | |
269 | // default secutiry attributes | |
270 | SECURITY_ATTRIBUTES security; | |
271 | ||
272 | security.nLength = sizeof(security); | |
273 | security.lpSecurityDescriptor = NULL; | |
274 | security.bInheritHandle = TRUE; // to pass it to the child | |
275 | ||
276 | if ( !::CreatePipe(&m_handles[0], &m_handles[1], &security, 0) ) | |
277 | { | |
278 | wxLogSysError(_("Failed to create an anonymous pipe")); | |
279 | ||
280 | return false; | |
281 | } | |
282 | ||
283 | return true; | |
284 | } | |
285 | ||
286 | // return true if we were created successfully | |
287 | bool IsOk() const { return m_handles[Read] != INVALID_HANDLE_VALUE; } | |
288 | ||
289 | // return the descriptor for one of the pipe ends | |
290 | HANDLE operator[](Direction which) const { return m_handles[which]; } | |
291 | ||
292 | // detach a descriptor, meaning that the pipe dtor won't close it, and | |
293 | // return it | |
294 | HANDLE Detach(Direction which) | |
295 | { | |
296 | HANDLE handle = m_handles[which]; | |
297 | m_handles[which] = INVALID_HANDLE_VALUE; | |
298 | ||
299 | return handle; | |
300 | } | |
301 | ||
302 | // close the pipe descriptors | |
303 | void Close() | |
304 | { | |
305 | for ( size_t n = 0; n < WXSIZEOF(m_handles); n++ ) | |
306 | { | |
307 | if ( m_handles[n] != INVALID_HANDLE_VALUE ) | |
308 | { | |
309 | ::CloseHandle(m_handles[n]); | |
310 | m_handles[n] = INVALID_HANDLE_VALUE; | |
311 | } | |
312 | } | |
313 | } | |
314 | ||
315 | // dtor closes the pipe descriptors | |
316 | ~wxPipe() { Close(); } | |
317 | ||
318 | private: | |
319 | HANDLE m_handles[2]; | |
320 | }; | |
321 | ||
322 | #endif // wxUSE_STREAMS | |
323 | ||
324 | // ============================================================================ | |
325 | // implementation | |
326 | // ============================================================================ | |
327 | ||
328 | // ---------------------------------------------------------------------------- | |
329 | // process termination detecting support | |
330 | // ---------------------------------------------------------------------------- | |
331 | ||
332 | // thread function for the thread monitoring the process termination | |
333 | static DWORD __stdcall wxExecuteThread(void *arg) | |
334 | { | |
335 | wxExecuteData * const data = (wxExecuteData *)arg; | |
336 | ||
337 | // create the shutdown event if we're the first thread starting to wait | |
338 | if ( !gs_heventShutdown ) | |
339 | { | |
340 | // create a manual initially non-signalled event object | |
341 | gs_heventShutdown = ::CreateEvent(NULL, TRUE, FALSE, NULL); | |
342 | if ( !gs_heventShutdown ) | |
343 | { | |
344 | wxLogDebug(wxT("CreateEvent() in wxExecuteThread failed")); | |
345 | } | |
346 | } | |
347 | ||
348 | HANDLE handles[2] = { data->hProcess, gs_heventShutdown }; | |
349 | switch ( ::WaitForMultipleObjects(2, handles, FALSE, INFINITE) ) | |
350 | { | |
351 | case WAIT_OBJECT_0: | |
352 | // process terminated, get its exit code | |
353 | if ( !::GetExitCodeProcess(data->hProcess, &data->dwExitCode) ) | |
354 | { | |
355 | wxLogLastError(wxT("GetExitCodeProcess")); | |
356 | } | |
357 | ||
358 | wxASSERT_MSG( data->dwExitCode != STILL_ACTIVE, | |
359 | wxT("process should have terminated") ); | |
360 | ||
361 | // send a message indicating process termination to the window | |
362 | ::SendMessage(data->hWnd, wxWM_PROC_TERMINATED, 0, (LPARAM)data); | |
363 | break; | |
364 | ||
365 | case WAIT_OBJECT_0 + 1: | |
366 | // we're shutting down but the process is still running -- leave it | |
367 | // run but clean up the associated data | |
368 | if ( !data->state ) | |
369 | { | |
370 | delete data; | |
371 | } | |
372 | //else: exiting while synchronously executing process is still | |
373 | // running? this shouldn't happen... | |
374 | break; | |
375 | ||
376 | default: | |
377 | wxLogDebug(wxT("Waiting for the process termination failed!")); | |
378 | } | |
379 | ||
380 | return 0; | |
381 | } | |
382 | ||
383 | // window procedure of a hidden window which is created just to receive | |
384 | // the notification message when a process exits | |
385 | LRESULT APIENTRY _EXPORT wxExecuteWindowCbk(HWND hWnd, UINT message, | |
386 | WPARAM wParam, LPARAM lParam) | |
387 | { | |
388 | if ( message == wxWM_PROC_TERMINATED ) | |
389 | { | |
390 | DestroyWindow(hWnd); // we don't need it any more | |
391 | ||
392 | wxExecuteData * const data = (wxExecuteData *)lParam; | |
393 | if ( data->handler ) | |
394 | { | |
395 | data->handler->OnTerminate((int)data->dwProcessId, | |
396 | (int)data->dwExitCode); | |
397 | } | |
398 | ||
399 | if ( data->state ) | |
400 | { | |
401 | // we're executing synchronously, tell the waiting thread | |
402 | // that the process finished | |
403 | data->state = false; | |
404 | } | |
405 | else | |
406 | { | |
407 | // asynchronous execution - we should do the clean up | |
408 | delete data; | |
409 | } | |
410 | ||
411 | return 0; | |
412 | } | |
413 | else | |
414 | { | |
415 | return ::DefWindowProc(hWnd, message, wParam, lParam); | |
416 | } | |
417 | } | |
418 | ||
419 | // ============================================================================ | |
420 | // implementation of IO redirection support classes | |
421 | // ============================================================================ | |
422 | ||
423 | #if wxUSE_STREAMS && !defined(__WXWINCE__) | |
424 | ||
425 | // ---------------------------------------------------------------------------- | |
426 | // wxPipeInputStreams | |
427 | // ---------------------------------------------------------------------------- | |
428 | ||
429 | wxPipeInputStream::wxPipeInputStream(HANDLE hInput) | |
430 | { | |
431 | m_hInput = hInput; | |
432 | } | |
433 | ||
434 | wxPipeInputStream::~wxPipeInputStream() | |
435 | { | |
436 | if ( m_hInput != INVALID_HANDLE_VALUE ) | |
437 | ::CloseHandle(m_hInput); | |
438 | } | |
439 | ||
440 | bool wxPipeInputStream::CanRead() const | |
441 | { | |
442 | // we can read if there's something in the put back buffer | |
443 | // even pipe is closed | |
444 | if ( m_wbacksize > m_wbackcur ) | |
445 | return true; | |
446 | ||
447 | wxPipeInputStream * const self = wxConstCast(this, wxPipeInputStream); | |
448 | ||
449 | if ( !IsOpened() ) | |
450 | { | |
451 | // set back to mark Eof as it may have been unset by Ungetch() | |
452 | self->m_lasterror = wxSTREAM_EOF; | |
453 | return false; | |
454 | } | |
455 | ||
456 | DWORD nAvailable; | |
457 | ||
458 | // function name is misleading, it works with anon pipes as well | |
459 | DWORD rc = ::PeekNamedPipe | |
460 | ( | |
461 | m_hInput, // handle | |
462 | NULL, 0, // ptr to buffer and its size | |
463 | NULL, // [out] bytes read | |
464 | &nAvailable, // [out] bytes available | |
465 | NULL // [out] bytes left | |
466 | ); | |
467 | ||
468 | if ( !rc ) | |
469 | { | |
470 | if ( ::GetLastError() != ERROR_BROKEN_PIPE ) | |
471 | { | |
472 | // unexpected error | |
473 | wxLogLastError(wxT("PeekNamedPipe")); | |
474 | } | |
475 | ||
476 | // don't try to continue reading from a pipe if an error occurred or if | |
477 | // it had been closed | |
478 | ::CloseHandle(m_hInput); | |
479 | ||
480 | self->m_hInput = INVALID_HANDLE_VALUE; | |
481 | self->m_lasterror = wxSTREAM_EOF; | |
482 | ||
483 | nAvailable = 0; | |
484 | } | |
485 | ||
486 | return nAvailable != 0; | |
487 | } | |
488 | ||
489 | size_t wxPipeInputStream::OnSysRead(void *buffer, size_t len) | |
490 | { | |
491 | if ( !IsOpened() ) | |
492 | { | |
493 | m_lasterror = wxSTREAM_EOF; | |
494 | ||
495 | return 0; | |
496 | } | |
497 | ||
498 | DWORD bytesRead; | |
499 | if ( !::ReadFile(m_hInput, buffer, len, &bytesRead, NULL) ) | |
500 | { | |
501 | m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE | |
502 | ? wxSTREAM_EOF | |
503 | : wxSTREAM_READ_ERROR; | |
504 | } | |
505 | ||
506 | // bytesRead is set to 0, as desired, if an error occurred | |
507 | return bytesRead; | |
508 | } | |
509 | ||
510 | // ---------------------------------------------------------------------------- | |
511 | // wxPipeOutputStream | |
512 | // ---------------------------------------------------------------------------- | |
513 | ||
514 | wxPipeOutputStream::wxPipeOutputStream(HANDLE hOutput) | |
515 | { | |
516 | m_hOutput = hOutput; | |
517 | ||
518 | // unblock the pipe to prevent deadlocks when we're writing to the pipe | |
519 | // from which the child process can't read because it is writing in its own | |
520 | // end of it | |
521 | DWORD mode = PIPE_READMODE_BYTE | PIPE_NOWAIT; | |
522 | if ( !::SetNamedPipeHandleState | |
523 | ( | |
524 | m_hOutput, | |
525 | &mode, | |
526 | NULL, // collection count (we don't set it) | |
527 | NULL // timeout (we don't set it neither) | |
528 | ) ) | |
529 | { | |
530 | wxLogLastError(wxT("SetNamedPipeHandleState(PIPE_NOWAIT)")); | |
531 | } | |
532 | } | |
533 | ||
534 | bool wxPipeOutputStream::Close() | |
535 | { | |
536 | return ::CloseHandle(m_hOutput) != 0; | |
537 | } | |
538 | ||
539 | ||
540 | size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t len) | |
541 | { | |
542 | m_lasterror = wxSTREAM_NO_ERROR; | |
543 | ||
544 | DWORD totalWritten = 0; | |
545 | while ( len > 0 ) | |
546 | { | |
547 | DWORD chunkWritten; | |
548 | if ( !::WriteFile(m_hOutput, buffer, len, &chunkWritten, NULL) ) | |
549 | { | |
550 | m_lasterror = ::GetLastError() == ERROR_BROKEN_PIPE | |
551 | ? wxSTREAM_EOF | |
552 | : wxSTREAM_WRITE_ERROR; | |
553 | break; | |
554 | } | |
555 | ||
556 | if ( !chunkWritten ) | |
557 | break; | |
558 | ||
559 | buffer = (char *)buffer + chunkWritten; | |
560 | totalWritten += chunkWritten; | |
561 | len -= chunkWritten; | |
562 | } | |
563 | ||
564 | return totalWritten; | |
565 | } | |
566 | ||
567 | #endif // wxUSE_STREAMS | |
568 | ||
569 | // ============================================================================ | |
570 | // wxExecute functions family | |
571 | // ============================================================================ | |
572 | ||
573 | #if wxUSE_IPC | |
574 | ||
575 | // connect to the given server via DDE and ask it to execute the command | |
576 | bool | |
577 | wxExecuteDDE(const wxString& ddeServer, | |
578 | const wxString& ddeTopic, | |
579 | const wxString& ddeCommand) | |
580 | { | |
581 | bool ok wxDUMMY_INITIALIZE(false); | |
582 | ||
583 | wxDDEClient client; | |
584 | wxConnectionBase * | |
585 | conn = client.MakeConnection(wxEmptyString, ddeServer, ddeTopic); | |
586 | if ( !conn ) | |
587 | { | |
588 | ok = false; | |
589 | } | |
590 | else // connected to DDE server | |
591 | { | |
592 | // the added complication here is that although most programs use | |
593 | // XTYP_EXECUTE for their DDE API, some important ones -- like Word | |
594 | // and other MS stuff - use XTYP_REQUEST! | |
595 | // | |
596 | // moreover, anotheri mportant program (IE) understands both but | |
597 | // returns an error from Execute() so we must try Request() first | |
598 | // to avoid doing it twice | |
599 | { | |
600 | // we're prepared for this one to fail, so don't show errors | |
601 | wxLogNull noErrors; | |
602 | ||
603 | ok = conn->Request(ddeCommand) != NULL; | |
604 | } | |
605 | ||
606 | if ( !ok ) | |
607 | { | |
608 | // now try execute -- but show the errors | |
609 | ok = conn->Execute(ddeCommand); | |
610 | } | |
611 | } | |
612 | ||
613 | return ok; | |
614 | } | |
615 | ||
616 | #endif // wxUSE_IPC | |
617 | ||
618 | long wxExecute(const wxString& cmd, int flags, wxProcess *handler, | |
619 | const wxExecuteEnv *env) | |
620 | { | |
621 | wxCHECK_MSG( !cmd.empty(), 0, wxT("empty command in wxExecute") ); | |
622 | ||
623 | #if wxUSE_THREADS | |
624 | // for many reasons, the code below breaks down if it's called from another | |
625 | // thread -- this could be fixed, but as Unix versions don't support this | |
626 | // neither I don't want to waste time on this now | |
627 | wxASSERT_MSG( wxThread::IsMain(), | |
628 | wxT("wxExecute() can be called only from the main thread") ); | |
629 | #endif // wxUSE_THREADS | |
630 | ||
631 | wxString command; | |
632 | ||
633 | #if wxUSE_IPC | |
634 | // DDE hack: this is really not pretty, but we need to allow this for | |
635 | // transparent handling of DDE servers in wxMimeTypesManager. Usually it | |
636 | // returns the command which should be run to view/open/... a file of the | |
637 | // given type. Sometimes, however, this command just launches the server | |
638 | // and an additional DDE request must be made to really open the file. To | |
639 | // keep all this well hidden from the application, we allow a special form | |
640 | // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which | |
641 | // case we execute just <command> and process the rest below | |
642 | wxString ddeServer, ddeTopic, ddeCommand; | |
643 | static const size_t lenDdePrefix = 7; // strlen("WX_DDE:") | |
644 | if ( cmd.Left(lenDdePrefix) == wxT("WX_DDE#") ) | |
645 | { | |
646 | // speed up the concatenations below | |
647 | ddeServer.reserve(256); | |
648 | ddeTopic.reserve(256); | |
649 | ddeCommand.reserve(256); | |
650 | ||
651 | const wxChar *p = cmd.c_str() + 7; | |
652 | while ( *p && *p != wxT('#') ) | |
653 | { | |
654 | command += *p++; | |
655 | } | |
656 | ||
657 | if ( *p ) | |
658 | { | |
659 | // skip '#' | |
660 | p++; | |
661 | } | |
662 | else | |
663 | { | |
664 | wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute")); | |
665 | } | |
666 | ||
667 | while ( *p && *p != wxT('#') ) | |
668 | { | |
669 | ddeServer += *p++; | |
670 | } | |
671 | ||
672 | if ( *p ) | |
673 | { | |
674 | // skip '#' | |
675 | p++; | |
676 | } | |
677 | else | |
678 | { | |
679 | wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute")); | |
680 | } | |
681 | ||
682 | while ( *p && *p != wxT('#') ) | |
683 | { | |
684 | ddeTopic += *p++; | |
685 | } | |
686 | ||
687 | if ( *p ) | |
688 | { | |
689 | // skip '#' | |
690 | p++; | |
691 | } | |
692 | else | |
693 | { | |
694 | wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute")); | |
695 | } | |
696 | ||
697 | while ( *p ) | |
698 | { | |
699 | ddeCommand += *p++; | |
700 | } | |
701 | ||
702 | // if we want to just launch the program and not wait for its | |
703 | // termination, try to execute DDE command right now, it can succeed if | |
704 | // the process is already running - but as it fails if it's not | |
705 | // running, suppress any errors it might generate | |
706 | if ( !(flags & wxEXEC_SYNC) ) | |
707 | { | |
708 | wxLogNull noErrors; | |
709 | if ( wxExecuteDDE(ddeServer, ddeTopic, ddeCommand) ) | |
710 | { | |
711 | // a dummy PID - this is a hack, of course, but it's well worth | |
712 | // it as we don't open a new server each time we're called | |
713 | // which would be quite bad | |
714 | return -1; | |
715 | } | |
716 | } | |
717 | } | |
718 | else | |
719 | #endif // wxUSE_IPC | |
720 | { | |
721 | // no DDE | |
722 | command = cmd; | |
723 | } | |
724 | ||
725 | // the IO redirection is only supported with wxUSE_STREAMS | |
726 | BOOL redirect = FALSE; | |
727 | ||
728 | #if wxUSE_STREAMS && !defined(__WXWINCE__) | |
729 | wxPipe pipeIn, pipeOut, pipeErr; | |
730 | ||
731 | // we'll save here the copy of pipeIn[Write] | |
732 | HANDLE hpipeStdinWrite = INVALID_HANDLE_VALUE; | |
733 | ||
734 | // open the pipes to which child process IO will be redirected if needed | |
735 | if ( handler && handler->IsRedirected() ) | |
736 | { | |
737 | // create pipes for redirecting stdin, stdout and stderr | |
738 | if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() ) | |
739 | { | |
740 | wxLogSysError(_("Failed to redirect the child process IO")); | |
741 | ||
742 | // indicate failure: we need to return different error code | |
743 | // depending on the sync flag | |
744 | return flags & wxEXEC_SYNC ? -1 : 0; | |
745 | } | |
746 | ||
747 | redirect = TRUE; | |
748 | } | |
749 | #endif // wxUSE_STREAMS | |
750 | ||
751 | // create the process | |
752 | STARTUPINFO si; | |
753 | wxZeroMemory(si); | |
754 | si.cb = sizeof(si); | |
755 | ||
756 | #if wxUSE_STREAMS && !defined(__WXWINCE__) | |
757 | if ( redirect ) | |
758 | { | |
759 | si.dwFlags = STARTF_USESTDHANDLES; | |
760 | ||
761 | si.hStdInput = pipeIn[wxPipe::Read]; | |
762 | si.hStdOutput = pipeOut[wxPipe::Write]; | |
763 | si.hStdError = pipeErr[wxPipe::Write]; | |
764 | ||
765 | // we must duplicate the handle to the write side of stdin pipe to make | |
766 | // it non inheritable: indeed, we must close the writing end of pipeIn | |
767 | // before launching the child process as otherwise this handle will be | |
768 | // inherited by the child which will never close it and so the pipe | |
769 | // will never be closed and the child will be left stuck in ReadFile() | |
770 | HANDLE pipeInWrite = pipeIn.Detach(wxPipe::Write); | |
771 | if ( !::DuplicateHandle | |
772 | ( | |
773 | ::GetCurrentProcess(), | |
774 | pipeInWrite, | |
775 | ::GetCurrentProcess(), | |
776 | &hpipeStdinWrite, | |
777 | 0, // desired access: unused here | |
778 | FALSE, // not inherited | |
779 | DUPLICATE_SAME_ACCESS // same access as for src handle | |
780 | ) ) | |
781 | { | |
782 | wxLogLastError(wxT("DuplicateHandle")); | |
783 | } | |
784 | ||
785 | ::CloseHandle(pipeInWrite); | |
786 | } | |
787 | #endif // wxUSE_STREAMS | |
788 | ||
789 | // The default logic for showing the console is to show it only if the IO | |
790 | // is not redirected however wxEXEC_{SHOW,HIDE}_CONSOLE flags can be | |
791 | // explicitly specified to change it. | |
792 | if ( (flags & wxEXEC_HIDE_CONSOLE) || | |
793 | (redirect && !(flags & wxEXEC_SHOW_CONSOLE)) ) | |
794 | { | |
795 | si.dwFlags |= STARTF_USESHOWWINDOW; | |
796 | si.wShowWindow = SW_HIDE; | |
797 | } | |
798 | ||
799 | ||
800 | PROCESS_INFORMATION pi; | |
801 | DWORD dwFlags = CREATE_SUSPENDED; | |
802 | ||
803 | #ifndef __WXWINCE__ | |
804 | if ( (flags & wxEXEC_MAKE_GROUP_LEADER) && | |
805 | (wxGetOsVersion() == wxOS_WINDOWS_NT) ) | |
806 | dwFlags |= CREATE_NEW_PROCESS_GROUP; | |
807 | ||
808 | dwFlags |= CREATE_DEFAULT_ERROR_MODE ; | |
809 | #else | |
810 | // we are assuming commands without spaces for now | |
811 | wxString moduleName = command.BeforeFirst(wxT(' ')); | |
812 | wxString arguments = command.AfterFirst(wxT(' ')); | |
813 | #endif | |
814 | ||
815 | wxWxCharBuffer envBuffer; | |
816 | bool useCwd = false; | |
817 | if ( env ) | |
818 | { | |
819 | useCwd = !env->cwd.empty(); | |
820 | ||
821 | // Translate environment variable map into NUL-terminated list of | |
822 | // NUL-terminated strings. | |
823 | if ( !env->env.empty() ) | |
824 | { | |
825 | #if wxUSE_UNICODE | |
826 | // Environment variables can contain non-ASCII characters. We could | |
827 | // check for it and not use this flag if everything is really ASCII | |
828 | // only but there doesn't seem to be any reason to do it so just | |
829 | // assume Unicode by default. | |
830 | dwFlags |= CREATE_UNICODE_ENVIRONMENT; | |
831 | #endif // wxUSE_UNICODE | |
832 | ||
833 | wxEnvVariableHashMap::const_iterator it; | |
834 | ||
835 | size_t envSz = 1; // ending '\0' | |
836 | for ( it = env->env.begin(); it != env->env.end(); ++it ) | |
837 | { | |
838 | // Add size of env variable name and value, and '=' char and | |
839 | // ending '\0' | |
840 | envSz += it->first.length() + it->second.length() + 2; | |
841 | } | |
842 | ||
843 | envBuffer.extend(envSz); | |
844 | ||
845 | wxChar *p = envBuffer.data(); | |
846 | for ( it = env->env.begin(); it != env->env.end(); ++it ) | |
847 | { | |
848 | const wxString line = it->first + wxS("=") + it->second; | |
849 | ||
850 | // Include the trailing NUL which will always terminate the | |
851 | // buffer returned by t_str(). | |
852 | const size_t len = line.length() + 1; | |
853 | ||
854 | wxTmemcpy(p, line.t_str(), len); | |
855 | ||
856 | p += len; | |
857 | } | |
858 | ||
859 | // And another NUL to terminate the list of NUL-terminated strings. | |
860 | *p = 0; | |
861 | } | |
862 | } | |
863 | ||
864 | // Translate wxWidgets priority to Windows conventions. | |
865 | if ( handler ) | |
866 | { | |
867 | unsigned prio = handler->GetPriority(); | |
868 | if ( prio <= 20 ) | |
869 | dwFlags |= IDLE_PRIORITY_CLASS; | |
870 | else if ( prio <= 40 ) | |
871 | dwFlags |= BELOW_NORMAL_PRIORITY_CLASS; | |
872 | else if ( prio <= 60 ) | |
873 | dwFlags |= NORMAL_PRIORITY_CLASS; | |
874 | else if ( prio <= 80 ) | |
875 | dwFlags |= ABOVE_NORMAL_PRIORITY_CLASS; | |
876 | else if ( prio <= 99 ) | |
877 | dwFlags |= HIGH_PRIORITY_CLASS; | |
878 | else if ( prio <= 100 ) | |
879 | dwFlags |= REALTIME_PRIORITY_CLASS; | |
880 | else | |
881 | { | |
882 | wxFAIL_MSG(wxT("invalid value of thread priority parameter")); | |
883 | dwFlags |= NORMAL_PRIORITY_CLASS; | |
884 | } | |
885 | } | |
886 | ||
887 | bool ok = ::CreateProcess | |
888 | ( | |
889 | // WinCE requires appname to be non null | |
890 | // Win32 allows for null | |
891 | #ifdef __WXWINCE__ | |
892 | moduleName.t_str(), // application name | |
893 | wxMSW_CONV_LPTSTR(arguments), // arguments | |
894 | #else | |
895 | NULL, // application name (use only cmd line) | |
896 | wxMSW_CONV_LPTSTR(command), // full command line | |
897 | #endif | |
898 | NULL, // security attributes: defaults for both | |
899 | NULL, // the process and its main thread | |
900 | redirect, // inherit handles if we use pipes | |
901 | dwFlags, // process creation flags | |
902 | envBuffer.data(), // environment (may be NULL which is fine) | |
903 | useCwd // initial working directory | |
904 | ? wxMSW_CONV_LPTSTR(env->cwd) | |
905 | : NULL, // (or use the same) | |
906 | &si, // startup info (unused here) | |
907 | &pi // process info | |
908 | ) != 0; | |
909 | ||
910 | #if wxUSE_STREAMS && !defined(__WXWINCE__) | |
911 | // we can close the pipe ends used by child anyhow | |
912 | if ( redirect ) | |
913 | { | |
914 | ::CloseHandle(pipeIn.Detach(wxPipe::Read)); | |
915 | ::CloseHandle(pipeOut.Detach(wxPipe::Write)); | |
916 | ::CloseHandle(pipeErr.Detach(wxPipe::Write)); | |
917 | } | |
918 | #endif // wxUSE_STREAMS | |
919 | ||
920 | if ( !ok ) | |
921 | { | |
922 | #if wxUSE_STREAMS && !defined(__WXWINCE__) | |
923 | // close the other handles too | |
924 | if ( redirect ) | |
925 | { | |
926 | ::CloseHandle(pipeOut.Detach(wxPipe::Read)); | |
927 | ::CloseHandle(pipeErr.Detach(wxPipe::Read)); | |
928 | } | |
929 | #endif // wxUSE_STREAMS | |
930 | ||
931 | wxLogSysError(_("Execution of command '%s' failed"), command.c_str()); | |
932 | ||
933 | return flags & wxEXEC_SYNC ? -1 : 0; | |
934 | } | |
935 | ||
936 | #if wxUSE_STREAMS && !defined(__WXWINCE__) | |
937 | // the input buffer bufOut is connected to stdout, this is why it is | |
938 | // called bufOut and not bufIn | |
939 | wxStreamTempInputBuffer bufOut, | |
940 | bufErr; | |
941 | ||
942 | if ( redirect ) | |
943 | { | |
944 | // We can now initialize the wxStreams | |
945 | wxPipeInputStream * | |
946 | outStream = new wxPipeInputStream(pipeOut.Detach(wxPipe::Read)); | |
947 | wxPipeInputStream * | |
948 | errStream = new wxPipeInputStream(pipeErr.Detach(wxPipe::Read)); | |
949 | wxPipeOutputStream * | |
950 | inStream = new wxPipeOutputStream(hpipeStdinWrite); | |
951 | ||
952 | handler->SetPipeStreams(outStream, inStream, errStream); | |
953 | ||
954 | bufOut.Init(outStream); | |
955 | bufErr.Init(errStream); | |
956 | } | |
957 | #endif // wxUSE_STREAMS | |
958 | ||
959 | // create a hidden window to receive notification about process | |
960 | // termination | |
961 | HWND hwnd = wxCreateHiddenWindow | |
962 | ( | |
963 | &gs_classForHiddenWindow, | |
964 | wxMSWEXEC_WNDCLASSNAME, | |
965 | (WNDPROC)wxExecuteWindowCbk | |
966 | ); | |
967 | ||
968 | wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") ); | |
969 | ||
970 | // Alloc data | |
971 | wxExecuteData *data = new wxExecuteData; | |
972 | data->hProcess = pi.hProcess; | |
973 | data->dwProcessId = pi.dwProcessId; | |
974 | data->hWnd = hwnd; | |
975 | data->state = (flags & wxEXEC_SYNC) != 0; | |
976 | if ( flags & wxEXEC_SYNC ) | |
977 | { | |
978 | // handler may be !NULL for capturing program output, but we don't use | |
979 | // it wxExecuteData struct in this case | |
980 | data->handler = NULL; | |
981 | } | |
982 | else | |
983 | { | |
984 | // may be NULL or not | |
985 | data->handler = handler; | |
986 | ||
987 | if (handler) | |
988 | handler->SetPid(pi.dwProcessId); | |
989 | } | |
990 | ||
991 | DWORD tid; | |
992 | HANDLE hThread = ::CreateThread(NULL, | |
993 | 0, | |
994 | wxExecuteThread, | |
995 | (void *)data, | |
996 | 0, | |
997 | &tid); | |
998 | ||
999 | // resume process we created now - whether the thread creation succeeded or | |
1000 | // not | |
1001 | if ( ::ResumeThread(pi.hThread) == (DWORD)-1 ) | |
1002 | { | |
1003 | // ignore it - what can we do? | |
1004 | wxLogLastError(wxT("ResumeThread in wxExecute")); | |
1005 | } | |
1006 | ||
1007 | // close unneeded handle | |
1008 | if ( !::CloseHandle(pi.hThread) ) | |
1009 | { | |
1010 | wxLogLastError(wxT("CloseHandle(hThread)")); | |
1011 | } | |
1012 | ||
1013 | if ( !hThread ) | |
1014 | { | |
1015 | wxLogLastError(wxT("CreateThread in wxExecute")); | |
1016 | ||
1017 | DestroyWindow(hwnd); | |
1018 | delete data; | |
1019 | ||
1020 | // the process still started up successfully... | |
1021 | return pi.dwProcessId; | |
1022 | } | |
1023 | ||
1024 | gs_asyncThreads.push_back(hThread); | |
1025 | ||
1026 | #if wxUSE_IPC && !defined(__WXWINCE__) | |
1027 | // second part of DDE hack: now establish the DDE conversation with the | |
1028 | // just launched process | |
1029 | if ( !ddeServer.empty() ) | |
1030 | { | |
1031 | bool ddeOK; | |
1032 | ||
1033 | // give the process the time to init itself | |
1034 | // | |
1035 | // we use a very big timeout hoping that WaitForInputIdle() will return | |
1036 | // much sooner, but not INFINITE just in case the process hangs | |
1037 | // completely - like this we will regain control sooner or later | |
1038 | switch ( ::WaitForInputIdle(pi.hProcess, 10000 /* 10 seconds */) ) | |
1039 | { | |
1040 | default: | |
1041 | wxFAIL_MSG( wxT("unexpected WaitForInputIdle() return code") ); | |
1042 | // fall through | |
1043 | ||
1044 | case WAIT_FAILED: | |
1045 | wxLogLastError(wxT("WaitForInputIdle() in wxExecute")); | |
1046 | ||
1047 | case WAIT_TIMEOUT: | |
1048 | wxLogDebug(wxT("Timeout too small in WaitForInputIdle")); | |
1049 | ||
1050 | ddeOK = false; | |
1051 | break; | |
1052 | ||
1053 | case 0: | |
1054 | // ok, process ready to accept DDE requests | |
1055 | ddeOK = wxExecuteDDE(ddeServer, ddeTopic, ddeCommand); | |
1056 | } | |
1057 | ||
1058 | if ( !ddeOK ) | |
1059 | { | |
1060 | wxLogDebug(wxT("Failed to send DDE request to the process \"%s\"."), | |
1061 | cmd.c_str()); | |
1062 | } | |
1063 | } | |
1064 | #endif // wxUSE_IPC | |
1065 | ||
1066 | if ( !(flags & wxEXEC_SYNC) ) | |
1067 | { | |
1068 | // clean up will be done when the process terminates | |
1069 | ||
1070 | // return the pid | |
1071 | return pi.dwProcessId; | |
1072 | } | |
1073 | ||
1074 | wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL; | |
1075 | wxCHECK_MSG( traits, -1, wxT("no wxAppTraits in wxExecute()?") ); | |
1076 | ||
1077 | void *cookie = NULL; | |
1078 | if ( !(flags & wxEXEC_NODISABLE) ) | |
1079 | { | |
1080 | // disable all app windows while waiting for the child process to finish | |
1081 | cookie = traits->BeforeChildWaitLoop(); | |
1082 | } | |
1083 | ||
1084 | // wait until the child process terminates | |
1085 | while ( data->state ) | |
1086 | { | |
1087 | #if wxUSE_STREAMS && !defined(__WXWINCE__) | |
1088 | if ( !bufOut.Update() && !bufErr.Update() ) | |
1089 | #endif // wxUSE_STREAMS | |
1090 | { | |
1091 | // don't eat 100% of the CPU -- ugly but anything else requires | |
1092 | // real async IO which we don't have for the moment | |
1093 | ::Sleep(50); | |
1094 | } | |
1095 | ||
1096 | // we must always process messages for our hidden window or we'd never | |
1097 | // get wxWM_PROC_TERMINATED and so this loop would never terminate | |
1098 | MSG msg; | |
1099 | ::PeekMessage(&msg, data->hWnd, 0, 0, PM_REMOVE); | |
1100 | ||
1101 | // we may also need to process messages for all the other application | |
1102 | // windows | |
1103 | if ( !(flags & wxEXEC_NOEVENTS) ) | |
1104 | { | |
1105 | wxEventLoopBase * const loop = wxEventLoopBase::GetActive(); | |
1106 | if ( loop ) | |
1107 | loop->Yield(); | |
1108 | } | |
1109 | } | |
1110 | ||
1111 | if ( !(flags & wxEXEC_NODISABLE) ) | |
1112 | { | |
1113 | // reenable disabled windows back | |
1114 | traits->AfterChildWaitLoop(cookie); | |
1115 | } | |
1116 | ||
1117 | DWORD dwExitCode = data->dwExitCode; | |
1118 | delete data; | |
1119 | ||
1120 | // return the exit code | |
1121 | return dwExitCode; | |
1122 | } | |
1123 | ||
1124 | template <typename CharType> | |
1125 | long wxExecuteImpl(CharType **argv, int flags, wxProcess *handler, | |
1126 | const wxExecuteEnv *env) | |
1127 | { | |
1128 | wxString command; | |
1129 | command.reserve(1024); | |
1130 | ||
1131 | wxString arg; | |
1132 | for ( ;; ) | |
1133 | { | |
1134 | arg = *argv++; | |
1135 | ||
1136 | bool quote; | |
1137 | if ( arg.empty() ) | |
1138 | { | |
1139 | // we need to quote empty arguments, otherwise they'd just | |
1140 | // disappear | |
1141 | quote = true; | |
1142 | } | |
1143 | else // non-empty | |
1144 | { | |
1145 | // escape any quotes present in the string to avoid interfering | |
1146 | // with the command line parsing in the child process | |
1147 | arg.Replace("\"", "\\\"", true /* replace all */); | |
1148 | ||
1149 | // and quote any arguments containing the spaces to prevent them from | |
1150 | // being broken down | |
1151 | quote = arg.find_first_of(" \t") != wxString::npos; | |
1152 | } | |
1153 | ||
1154 | if ( quote ) | |
1155 | command += '\"' + arg + '\"'; | |
1156 | else | |
1157 | command += arg; | |
1158 | ||
1159 | if ( !*argv ) | |
1160 | break; | |
1161 | ||
1162 | command += ' '; | |
1163 | } | |
1164 | ||
1165 | return wxExecute(command, flags, handler, env); | |
1166 | } | |
1167 | ||
1168 | long wxExecute(char **argv, int flags, wxProcess *handler, | |
1169 | const wxExecuteEnv *env) | |
1170 | { | |
1171 | return wxExecuteImpl(argv, flags, handler, env); | |
1172 | } | |
1173 | ||
1174 | #if wxUSE_UNICODE | |
1175 | ||
1176 | long wxExecute(wchar_t **argv, int flags, wxProcess *handler, | |
1177 | const wxExecuteEnv *env) | |
1178 | { | |
1179 | return wxExecuteImpl(argv, flags, handler, env); | |
1180 | } | |
1181 | ||
1182 | #endif // wxUSE_UNICODE |